Checking if a number is palindrome - python-3.x

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.

Related

How to create a perfect number function using lists

My perfect number function is not working as intended :(. It prints false even though it should print true :(
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
You have put the if-else statement inside your for loop. It should be outside the for loop. Then, your code will work correctly.

Is there a better way to compare multiple functions?

Is there a better way of comparing functions within another function? How can I handle too many conditions without having ugly code?
#Function to Convert string to integer
def input(X):
if type (X) == str:
X = int(X)
return X
#Function to check input equality
def equality(A,B,C):
if input(A) == input(B) or input(B) == input(C) or input(C) == input(A):
return True
else:
return False
This will help you..
def input(X):
if type(X) == str or type(X) == int:
return int(X)
def equality(*argv):
tmp_list = []
for arg in argv:
tmp_list.append(input(arg))
return not len(tmp_list) == len(set(tmp_list))
I changed the function to work with *args and now you can check more than three at once.
>>> equality(10,11,20,20)
True
>>> equality(10,'11',20,'20')
True
>>> equality('10','20',30,'40')
False

Python how to check if it is a leap year with ==int

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)

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

Recursion: Palindromes [duplicate]

This question already has answers here:
Recursive Function palindrome in Python [closed]
(10 answers)
Closed 7 years ago.
So I have this code for detecting if a string is a palindrome (the same forward and backwards) and I'm not sure how to change it to a recursive program
def isPalindrome(string):
i = 0
j = len(string) - 1
k = 0
while (i <= j):
if string[j] != string[i]:
k = 1
else:
i += 1
j -= 1
if k == 0:
return True
else:
return False
def main():
print("This program tests if strings are palindromes.")
word = input("Enter a string: ")
while word != "quit" :
if isPalindrome(word) == True:
print(word,"is a palindrome.")
else:
print(word,"is not a palindrome.")
word = input("Enter a string: ")
main()
I'm really bad with recursions and I don't really understand them any help would be great. Thanks
Without Recursion:
Ideally you might not need recursion for palindrome detection. It can be done simply as below.
def is_palindrome(word):
if word=="".join(reversed(word)):
return True
return False
Another shorter method
def is_palindrome(word):
return word[::-1]==word
Using Recursions:
For some reasons if you still require recursion and comfortable with arrays and indices, Use it like this.
def is_palindrome(word, end=0, start=0):
if end == 0:
end = len(word)-1
if start >= end:
return True
if word[start] != word[end]:
return False
start = start+1
end = end-1
return is_palindrome(start, end, word)
word = 'ramar'
print (is_palindrome(word))
This will be more Pythonic way with recursion
def is_palindrome(word):
if not word:
return True
else:
return word[0]==word[-1] and is_palindrome(word[1:-1])

Resources