I'm trying to learn python more by solving the hacker rank puzzles and I can't understand why it is failing
This code is supposed to determine whether or not a year that is or above 1900 is, in fact, a leap year, the website says it passes 5 of 6 tests. For the input
2100 it's returning true instead of false.
def is_leap(year):
leap = False
if year%4==0:
return True
elif year%100==0:
return False
elif year%400==0:
return True
return leap
year = int(input())
print(is_leap(year))
I expect it to return false if the year is not divisible by 100 and return true if it is divisible by 4 or 400.
Let's see what happens if the year is, e.g. 1900, a year that was not a leap year:
Since year % 4 is 0, we return True immediately, which is of course wrong. In fact, any number that is divisible by 100 or 400 must also be divisible by 4, meaning that we never even get to the bottom two conditions.
So the solution is to reorder your conditions from most to least specific:
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
Your second misunderstanding has to do with return: A return statement doesn't somehow "mark" a value to be the return value at the end of the function, it immediately exits the function, returning that value. For better consistency, I would remove the leap variable, and just return False at the end of the function. Alternatively, you could assign to leap inside the conditions instead of returning there.
Your if statement is not changing the variable leap.
Try changing the variable leap like below.
def is_leap(year):
leap = False
if year%4==0:
leap = True
elif year%100==0:
leap = False
elif year%400==0:
leap = True
return leap
year = int(input())
print(is_leap(year))
def foo(year: int) -> bool:
"find a year is leapyear or not"
if year % 4 == 0 and year % 100 != 0:
return True
return year % 4 == 0 and year % 100 == 0 and year % 400 == 0
The function takes an integer as argument for the year parameter and returns True if the year is a leap year and False for the opposite. A year needs to be divisible by 4 and not by 100 to be a confirmed leap year. So, the conditional statement checks for that. If the condition's met it returns True else that function does not return anything and continues downward. Then, if the number is divisible by 4 and 100 and 400 as this case also means the year is a confirmed leap year, it returns True. We have done all checks and still if that's not True then certainly the years not a leap year.
Related
I have written a code for identifying leap year. It works perfectly but the code seems a bit off. I have added the code here. Plz someone confirm whether the code is correct or not.
the code
year = int(input("Which year do you want to check? "))
divided_by_4 = year % 4
divided_by_100 = year % 100
divided_by_400 = year % 400
if divided_by_4 == 0 and divided_by_400 == 0 or divided_by_100 != 0:
print("It is a leap year.")
else:
print("Not a leap year.")
A year is not a leap year if it is divisible by 100, unless it is divisible by 400, so you should test divided_by_100 != 0 first and then use the or operator to test divided_by_400 == 0 as a fallback. Since or has a lower operator precedence than and, you should enclose the or operation in parentheses:
if divided_by_4 == 0 and (divided_by_100 != 0 or divided_by_400 == 0):
print("It is a leap year.")
else:
print("Not a leap year.")
To begin, a definition:
A polydivisible number is an integer number where the first n digits of the number (from left to right) is perfectly divisible by n. For example, the integer 141 is polydivisible since:
1 % 1 == 0
14 % 2 == 0
141 % 3 == 0
I'm working on a recursive polydivisible checker, which, given a number, will check to see if that number is polydivisible, and if not, recursively check every other number after until it reaches a number that is polydivisible.
Unfortunately, my code doesn't work the way I want it to. Interestingly, when I input a number that is already polydivisible, it does its job and outputs that polydivisible number. The problem occurs when I input a non-polydivisible number, such as 13. The next polydivisible number should be 14, yet the program fails to output it. Instead, it gets stuck in an infinite loop until the memory runs out.
Here's the code I have:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
else:
return num
else:
print("Number must be non-negative")
return None
I'm assuming the problem occurs in the else statement inside the while loop, where, if the number fails to be polydivisible, the program resets i to 0, and adds 1 to the original number so it can start checking the new number. However, like I explained, it doesn't work the way I want it to.
Any idea what might be wrong with the code, and how to make sure it stops and outputs the correct polydivisible number when it reaches one (like 14)?
(Also note that this checker is only supposed to accept non-negative numbers, hence the initial if conditional)
The mistake is that you are no updating number after incrementing num.
Here is working code:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
number = str(num) # added line
else:
return num
else:
print("Number must be non-negative")
return None
I have a similar answer to #PranavaGande, the reason is I did not find any way to iterate an Int. Probably because there isn't one...Duh !!!
def is_polydivisible(n):
str_n = str(n)
list_2 = []
for i in range(len(str_n)):
list_2.append(len(str_n[:i+1]))
print(list_2)
list_1 = []
new_n = 0
for i in range(len(str_n)):
new_n = int(str_n[:i+1])
list_1.append(new_n)
print(list_1)
products_of_lists = []
for n1, n2 in zip(list_1, list_2):
products_of_lists.append(n1 % n2)
print(products_of_lists)
for val in products_of_lists:
if val != 0:
return False
return True
Now, I apologise for this many lines of code as it has to be smaller. However every integer has to be split individually and then divided by its index [Starting from 1 not 0]. Therefore I found it easier to list both of them and divide them index wise.
There is much shorter code than mine, however I hope this serves the purpose to find if the number is Polydivisible or Not. Of-Course you can tweak the code to find the values, where the quotient goes into decimals, returning a remainder which is Non-zero.
def is_leap(num):
if(num % 400 == 0):
print("The year {} is a leap year".format(num))
elif(num % 4 == 0 and num % 100!= 0):
print("The year {} is a leap year".format(num))
else:
print("The year {} is not a leap year".format(num))
return is_leap
year = is_leap(2000)
print(year
)
I get the result but it also mentions this - function is_leap at 0x101a581e0
how can I avoid this? I have tried to resolve this myself after googling I found that I am returning my own function but still I am not able to figure it out on which part of the code should I modify
In the function you return 'is_leap', which is the function itself, meaning after year = is_leap(2000), the year variable refers to the function itself, and you print that stored value. Since you already print your result inside is_leap(), there is no need for returning something, or for using
print(is_leap(x))
If you simply remove the return statement from the function and then call it like is_leap(2000)
you should achieve what you want.
def is_leap(num):
is_leap_year=False
if(num % 400 == 0):
is_leap_year=True
print("The year {} is a leap year".format(num))
elif(num % 4 == 0 and num % 100!= 0):
is_leap_year=True
print("The year {} is a leap year".format(num))
else:
print("The year {} is not a leap year".format(num))
return is_leap_year
year = is_leap(2000)
print(year)
I think you want to set boolean either it is leap year or not but you are returning funtion name and printing it which is reference address of function.
I run a while loop with a function to check if a variable i is higher than the len of the list. I placed it there as a way to stop the loop, but it does not check it. Since it doesn't end on it's own I had to place an if condition inside that returns false.
def binarySearch(numberlist, number):
first = 0
last = len(numberlist)-1
found = False
i=0
while found == False or i <= len(numberlist):
i = i + 1
mid = (first + last) // 2
print(numberlist[mid])
if i > len(numberlist)+1:
return False
if mid < first or mid > last or mid < 0:
return False
if number == numberlist[mid] or number == numberlist[first] or number == numberlist[last] :
return True
elif number < numberlist[mid]:
last = mid
elif number > numberlist[mid]:
first = mid
return False
The error lies in the following lines.
elif number < numberlist[mid]:
last = mid
elif number > numberlist[mid]:
first = mid
Consider the case where we are looking for a number which is not in the list.
The pointers first, last and mid will eventually all converge to some index. In that case one of the two last conditions will be True, but since all three values are already equal, the pointers are not updated anymore and we enter an infinite loop.
To makes sure this does not happen, we must make sure the interval always decreases in size by setting first to mid + 1 or last to mid - 1, depending on the condition. We can then stop looping if first becomes greater than last.
def binary_search(numberlist, number):
first, last = 0, len(numberlist) - 1
while first <= last:
mid = (first + last) // 2
if numberlist[mid] == number:
return True
elif numberlist[mid] > number:
last = mid - 1
else:
first = mid + 1
return False
I am trying to count how many times my program goes through my recursive statement and gives me my result. This is the code:
def days(amt):
day = 0
new = (amt*.05) + amt - 10
if amt == 0:
return 0
elif amt == '':
return
elif new >= 0 and new <= 1000:
day += 1
return days(new)
print("In {} days, you'll have {}".format(day,new))
So when you call the function days(100), it calculates that it takes 15 days to reach new amount which less than 0 or greater than 1000 (and then it stops bc it satisfies the second elif condition).
So I want my output to look like this In 15 days, you'll have -7.892....
My problem is no matter where I place the counter, it doesn't count.
To persist the count you need to either use some global variable or use a parameter to do the counting then return both the count and the amt:
def days(amt, day=1):
new = (amt * .05) + amt - 10
if amt == 0:
return day, 0
elif 0 <= new <= 1000:
return days(new, day + 1)
return day, new
Which gives you:
In [2]: print("In {} days, you'll have {}".format(*days(100)))
In 15 days, you'll have -7.89281794114
You cannot set day = 0 anywhere in the function as every call is going to reset it to 0. I also removes elif amt == '' as I cannot see how a function that takes an int/float should ever equal to an empty string.