Python how to check if it is a leap year with ==int - python-3.x

def leapyear(year):
if year/400 == int :
return False
if year/100 == int :
return False
if year/4 == int :
return True
hello I would like to know why my code doesn't work with it == to int because essentially its the same thing as using modulo and == to 0 this is just a question that came to me.
def check(n): if n > 200: return "large"
x = n/2 if x !=int: return "odd"
elif x==0 and n< 100: return "small"
elif x==0 and n>100: return "medium"
also how come the int works here

Your issue is that int is a type. If you try to compare a number to a type of object, which is what you are doing when you write if year/400 == int :, it will always return False, because these can never be the same.
A better way to check if year/400 is an integer would be:
if year%400 == 0:
return False
This is saying:
If the remainder of year/400 is equal to 0, return False, which is what you wanted.
Some other things are:
You should use elif instead of if in most cases. In this one, it doesn't matter, since the return statement terminates the execution of the function early, but you should still use it anyways. Otherwise, even when you have your final result, it will go through the rest of the if statements.
The other thing isn't related to your code, but your leap year criteria are incorrect. If the year is divisible by 4, then it's a leap year.
Unless the year is divisible by 100, then it's not.
Unless it's divisible by 400, then it is.
Improved code:
def leapyear(year):
if year%400 == 0:
return True
elif year%100 == 0:
return False
elif year%4 == 0:
return True
return False

In Python int is considered as Class. You can use type() function on a variable to get it's datatype in Python. So, to use your logic you have to rewrite your code as below:
def leapyear(year):
if type(year/400) == int :
return False
if type(year/100) == int :
return False
if type(year/4) == int :
return True
Note: I have just replicated your code by adding the type() function wherever necessary but it would be suggested to use if, elif and else rather than just if, as it will optimize your code.

You are checking direct number not its type. You should use....
if type(year/400) == int :
Then here is the conditional block.
elif type(year/100) == int:
Another Conditional check
elif type(year/4) == int:
Another conditional block.
And you also have a logical error please see the complete code given below.
So your function can be re-written with corrected logic as...
def leap_year(year):
if type(year/400) == int :
return False
elif type(year/100) == int:
return False
elif type(year/4) == int:
return False
else:
return True
This is the Complete code.

You should know output is FLOAT if use '/' .
e.g.
2020/400 -> 5.05
2020/100 -> 20.2
2020/4 -> 505
You have to change type like using int()
e.g.
2020/400 -> 5.05 int(2020/400) -> 5
2020/100 -> 20.2 int(2020/100) -> 20
2020/4 -> 505 int(2020/4) -> 505
from __future__ import division
import sys
time_year = int(sys.argv[1])
def leapyear(year):
if (year/400) == int(year/400) :
result = False
elif (year/100) == int(year/100) :
result = False
elif (year/4) == int(year/4) :
result = True
else :
result = 'something worg'
return result
a=leapyear(time_year)
print a
Hope can help you :)

year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))

You can check a year whether it is leap year or not by returning True or False
without using any libraries.
(lambda year : (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0))(2020)

Related

Checking if a number is palindrome

I have this code for checking if a number is a palindrome and for some reason it returns false for number=1 even though it is palindrome. Why is that? The code works for other cases such as 12321.
def palindrome_integer(number):
if number != int:
return False
elif str(number) == str(number)[::-1]:
return True
else:
return False
If you want to check if number is integer, you should use isistance.
def palindrome_integer(number):
if not isinstance(number, int):
return False
elif str(number) == str(number)[::-1]:
return True
else:
return False
The rest of your code seems to work fine.
One-liner:
return isinstance(n, int) and str(n) == str(n)[::-1]
Or slightly more contrived:
import re
x = str(n)
return re.match(r”\d+“, x) and x == x[::-1]
solution without string
def palindrome_integer(num):
copy = num
rev = 0
while num!= 0:
rev = rev*10+num%10
num = num//10
return rev == copy
def palindrome_integer(number):
return type(number) == int and str(number)[::-1] == str(number)
Don't hesitate to comment if you have problem in understanding the solution.

Loop through a system argument in Python

This is a blackjack program. When stand function is false, main function is not supposed to append getCard() to myCards but for some reason it still does and it counts backwards. I don't know what I am doing wrong.
import random
import sys
def get_card():
return random.randint(1, 13)
def score(cards):
soft_ace_count = 0
total = 0
Ace = False
To check if an Ace exists in hand and to set face cards to correct value
for card in cards:
if card == 1:
Ace = True
total+=11
soft_ace_count+=1
elif card == 11 or card == 12 or card == 13:
total+=10
else:
total+=card
To convert Ace
for x in cards:
if Ace and total > 21:
total-=10
soft_ace_count-=1
return (total, soft_ace_count)
def stand(stand_on_value, stand_on_soft, cards):
total, soft_ace_count = score(cards)
print(f"In stand: {total}")
if total > 17 and total < 22:
return True
if total == stand_on_value:
return True
elif soft_ace_count == 0 and total == 17:
return True
elif stand_on_soft == True and total == 17:
return True
else:
return False
def numBusts(s):
total, soft_ace_count = s
busted_count = 0
if total > 21:
busted_count+=1
return busted_count
def main():
numSims = int(sys.argv[1])-1
standVal = int(sys.argv[2])
strategy = sys.argv[3]
strategy.upper()
for sims in range(numSims+1):
percent_bust = 0.0
myCards = [get_card(), get_card()]
print(f"in main: first two cards: {myCards}")
stand(standVal, strategy, myCards)
while not stand(standVal, strategy, myCards):
myCards.append(get_card())
percent_bust = (numBusts(score(myCards))/(numSims+1)) * 100
print(f"in main: percent bust: {percent_bust}")
if __name__ == "__main__":
[The image shows how it runs correctly until the while not stand function returns False.][1]main()
I have tried running for loops, not running loops, and other things.
Please help.
while not stand will append to the result of get_card() to myCards when stand is False.
But in your question, you say you don't want it to append when stand() is False.
Also, you seem to be calling the stand function twice consecutively, is this intended? The conditional actually calls the function in order to check its result.
Perhaps this will do what you expect?:
for sims in range(numSims+1):
percent_bust = 0.0
myCards = [get_card(), get_card()]
print(f"in main: first two cards: {myCards}")
if stand(standVal, strategy, myCards) is True:
myCards.append(get_card())
This conditional will append to myCards if and only if stand() returns True, but not when it returns False, 0, or None.

Is there a way i can avoid getting "None" when i print out my function?

I am trying to calculate the avarage grade of a subject. but when i print the function i get printed None.
And i do not know how to fix it.
Ive tried returning the value instead then printing the function, but it wont work.
def karakterKonversjon(bokstav):
if bokstav == 'A':
return 6
if bokstav == 'B':
return 5
if bokstav == 'C':
return 4
if bokstav == 'D':
return 3
if bokstav == 'E':
return 2
if bokstav == 'F':
return 1
def konversjonTilBokstav(tall):
if tall == 6:
return 'A'
if tall == 5:
return 'B'
if tall == 4:
return 'C'
if tall == 3:
return 'D'
if tall == 2:
return 'E'
if tall == 1:
return 'F'
def beregnSnitt():
nummer_karakter = 0
suM = 0
for i in emner:
if emner[i] != "":
tall_karakter = eksamen.karakterKonversjon(emner[i])
suM += (tall_karakter * studiepoeng)
suM /= totalPoeng
rundetSvar = eksamen.normal_round(suM)
eksamen.konversjonTilBokstav(rundetSvar)
print(rundetSvar)
def normal_round(suM):
if (float (suM) < 5):
print(math.floor(suM))
else:
print(math.ceil(suM))
THe result i am expecting is
4
C
But i am getting
4
None
I made a few modifications to your code:
(I assume you are importing math in the eksamen file)
def karakterKonversjon(bokstav): # make this function more efficient
atof = ['A','B','C','D','E','F']
for i in range(len(atof)):
if bokstav.upper() == atof[i]:
return len(atof) - i
def konversjonTilBokstav(tall): # make this function more efficient
atof = ['A','B','C','D','E','F']
for i in range(1,7):
if tall == i:
return atof[len(atof)-i]
def beregnSnitt():
nummer_karakter = 0
suM = 0
for i in range(len(emner)): # if enmer == "enmer"(for example) you cannot reference enmer['e'] without raising an error
if emner[i] != "":
tall_karakter = eksamen.karakterKonversjon(emner[i])
suM += (tall_karakter * studiepoeng)
suM /= totalPoeng
rundetSvar = eksamen.normal_round(suM)
eksamen.konversjonTilBokstav(rundetSvar)
print(rundetSvar)
def normal_round(suM):
if (float (suM) < 5):
print(math.floor(suM))
else:
print(math.ceil(suM))
apart from the differences i made, your code should work well however i cannot test without knowing what enmer is (i assume it's a string) or what studiepoeng is.
the function konversjonTilBokstav did work fine for me. But what I have included in the code snippet should be less spaghetti code

Finding the logical error in my code to get first 50 primes

I'm trying to write my own formula to find a prime number, but it does not completely work and I cannot find the flaw in my logic. Bare in mind I have taken a look around but cannot find an algorithm that I find similar to mine.
My code:
#Challenge 7
prime = []
num = 0
found = False
while found == False:
if num == 0 or num == 1:
num+=1
else:
for value in range(2, num+1):
if len(prime) == 50:
print('Found all')
found = True
break
if num % value == 0:
num+=1
else:
if num not in prime:
prime.append(num)
else:
pass
print(prime)
This code works for first few primes (3, 5, 7...)
but it also gives incorrect values like 10, and I don't understand why. If someone could explain it to me so that I can understand where the logical mistake is, I'd appreciate it.
The error comes from this part
if num % value == 0:
num+=1
else:
if num not in prime:
prime.append(num)
else:
pass
You assume that the integer is a prime as soon as we find the first occurence of a non-divisor. But the def for primes is that every integer in the interval [2..prime] is a non-divisor. How do we check if any number does not have any divisors?
def isPrime(x):
for v in range(2, x):
if (x % v == 0):
return False;
return True;
Something like this would work to check if any given number is a prime or not. And since we now have taken the isPrime part out of the main loop, we no longer need a for loop inside the while. Something like this would do
def isPrime(x):
for v in range(2, x):
if (x % v == 0):
return False;
return True;
prime = [}
num = 2
found = False
while found == False:
if len(prime) == 50:
print("found all")
found = True
break
if(isPrime(num)):
print(num)
prime.append(num)
num+=1
else:
num+=1
If you set a breakpoint for when num == 10 you will see the problem clearly.
When you start doing you division check inside of for value in range(2, num + 1): the second number is 3, so num (10) modulo value (3) is 1, which is your test for determining a prime. What your test should be is that it not divisible by any number less than it (less than half is actually sufficient since you check with 2 anyway).
So, consider instead:
else:
is_indivisible = True
# loop through all numbers less than it not including itself
# (because x % x == 0)
for value in range(2, num - 1):
# it is only indivisible if it was previously indivisible
# And the check is same as before, modulo != 0
is_indivisible = is_indivisible and (num % value != 0)
if not is_indivisible:
break
# if it is indivisible and it doesn't exist in prime list yet
if is_indivisible and num not in prime:
prime.append(num)
# move on to the next number
num += 1

Python: TypeError: 'int' object is not iterable

I'm tackling this following question:
Write a function is_fib(n) that returns True if n is a Fibonacci number, and False otherwise.
This is my code:
def is_fib(n):
def fib(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
for a in n:
if fib(a) == n:
result = True
break
else:
result = False
return result
Running this give rise to:
TypeError: 'int' object is not iterable.
I have been staring at the code for half an hour. Any help is greatly appreciated.
I think you mean
for a in range(n)
not
for a in n
As jozefg said you are missing range(n)
also notice that you need range(n+2) to cover all cases
def is_fib(n):
def fib(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
for a in range(n+2):
if fib(a) == n:
return True
return False
print(is_fib(3))
Firstly thanks to the two guys that helped me.
However, for Yoav's edition, python will run into an error when n is a really big number.
This is my new and improved version.
def is_fib(n):
if n < 0:
return False
else:
fib_0 = 0
fib_1 = 1
if n == fib_0 or n == fib_1:
return True
else:
for a in range(2,n+2):
fib = fib_0 + fib_1
fib_0,fib_1 = fib_1,fib
if fib >= n:
break
return fib == n

Resources