Using Python, reverse an integer, and tell if palindrome - python

Using Python, reverse an integer and determine if it is a palindrome. Here is my definition of reverse and palindrome. Do I have a correct logic?
def reverse(num):
s=len(num)
newnum=[None]*length
for i in num:
s=s-1
newnum[s]=i
return newnum
def palindrome(num):
a=str(num)
l=len(z)/2
if a[:1]==a[-1:][::-1]:
b=True
else:
b=False
I am having some trouble to write def main.

def palindrome(num):
return str(num) == str(num)[::-1]

Integer numbers don't have len().
Testing if a number is a palindrome is as simple as testing if the number is equal to its reverse (though if you want maximum efficiency you can just compare characters from both ends of the string until you reach the middle).
To find the reverse of an integer you can either do it the hard way (using mod % and integer division // to find each digit and construct the reverse number):
def reverse(num):
rev = 0
while num > 0:
rev = (10*rev) + num%10
num //= 10
return rev
Or the easy way (turning the number into a string, using slice notation to reverse the string and turning it back to an integer):
def reverse(num):
return int(str(num)[::-1])

This is an unreadable one-line recursive implementation based in part on the answer by pedrosorio.
def reverse(i):
return int(i!=0) and ((i%10)*(10**int(math.log(i,10))) + reverse(i//10))
def is_palindrome(i):
return i == reverse(i)
It works for integer i ≥ 0.
Note that reverse(123) == reverse(1230) == 321. This is not a problem, considering any nonzero integer that ends with 0 cannot be a palindrome anyway.
Note also that complete reversal of the integer may of course not be necessary to determine if it's a palindrome. The reversal may be implemented so as to be aborted early if the number is determined to not be a palindrome.

Long but readable:
def palindrome(x):
a=""
x=str(x)
for i in range(len(x),0,-1):
a+=x[i-1]
print a
if a==x:
return True
else:
return False

Reverse an integer and determine if it is a palindrome:
Convert integer to string.
Use reverse function to reverse the string and join it.
Check if reversed number = original number with if else condition.
See code:
number = 1221
reverse = ''.join(reversed(str(number)))
print(reverse)
if (int(reverse) == number):
print("number is Palindrome")
else:
print("number is not Palindrome")

def revers(num):
rev = 0
while num > 0:
rem = num % 10
rev = (rev * 10) + rem
num = num // 10
return rev

I used a list for this program, works with strings too.
print('Enter Something')
a = list(input())
for i in range ((len(a)),0,-1):
print (a[i-1],end='')

import math
a = raw_input("Enter number:")
n = -1
reverse = 0
for i in a:
n += 1
digit = math.pow(10,n)
reverse = int(i)*digit + reverse
print int(reverse)
if int(reverse) == int(a):
print "Palindrome"
else:
print ":("

This code converts int to String and then checks if the string is pallindrome. The advantage is that it is fast, the disadvantage being that it converts int to String thereby compromising with the perfect solution to question.
It handles negative int as well.
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
s = str(x)
if x >=0 :
if s == s[::-1]:
return True
else:
return False
else:
return False

t=int(input("enter nos of test cases= "))
while t>0:
n=int(input("enter number="))
rev=0
while n>0:
digit=n%10
rev=rev*10+digit
n=n//10
print(rev)
t-=1

Here is my solution.
z=input('input number')
if int(z) == int(str(z)[::-1]):
print('The number is palindrome')
else:
print('The number is not palindrome')

def pal_num(num):
if num<0:
print(False)
elif num == int(str(num)[::-1]):
print(True)
else:
print(False)
This example quickly takes care of the negative number edge case

I try to come out with this myself.
def number():
n = int(input("Enter a number: "))
return n
def reverse(n):
total = ""
while n > 0:
a = n % 10
n//= 10
total+= str(a)
return total
def palindrome (n):
total = 0
while n > 0:
a = n % 10
n//= 10
total+= a
if total == n:
x = "This number has a palindrome"
else:
x = ""
return x
n = number()
print (reverse(n))
print (palindrome(n))

original = raw_input("Enter a no = ") #original = number entered by user
rev = original[::-1] #rev = reverse of original by useing scope resolution
print 'rev of original no =',rev
if original == rev:
print "no's are equal"
else:
print "no's are not equal"

Related

Python Credit Card Check Function not running correctly

Trying to implement a program in Python that can check if the input is a valid credit card and display the credit card type(VISA/MASTERCARD/AMEX). For 2 values it's displaying incorrectly and for 2 days I have no ideas how to fix it ?
Output received:( last 2 are incorect 4111111111111113 and 4222222222223) I guess is something related with the check_last_digit function ....
identifies 378282246310005 as AMEX
:) identifies 371449635398431 as AMEX
:) identifies 5555555555554444 as MASTERCARD
:) identifies 5105105105105100 as MASTERCARD
:) identifies 4111111111111111 as VISA
:) identifies 4012888888881881 as VISA
:) identifies 4222222222222 as VISA
:) identifies 1234567890 as INVALID
:) identifies 369421438430814 as INVALID
:) identifies 4062901840 as INVALID
:) identifies 5673598276138003 as INVALID
:( **identifies 4111111111111113 as INVALID**
**expected "INVALID\n", not "VISA\n\n"**
:( **identifies 4222222222223 as INVALID**
**expected "INVALID\n", not "VISA\n\n**
My Code:
#function to find out the sum of every other numbers from the input card
def odd_sum(num):
num = list(str(num))
my_list_digits = [int(item) * 2 for item in num][::2]
total_odd = 0
for number in my_list_digits:
if number > 9:
first_digit = number // 10
second_digit = number % 10
total_odd += first_digit + second_digit
else:
total_odd += number
return total_odd
# function to find out the sum of the other remaining numbers
def even_sum(num):
num = list(str(num))
del num[::2]
my_list_digits1 = [int(item) for item in num]
total_even = 0
for item in my_list_digits1:
total_even += item
return total_even
# function to check the lenght of the input card
def check_length(num):
num = str(num)
num_length = len(num)
if 13 <= num_length <= 16:
return True
else:
print("INVALID")
# function to check the last digit of the sum ( even and odd)
def check_last_digit(num):
odd = odd_sum(num)
even = even_sum(num)
if (odd + even) % 10 == 0:
return True
else:
return False
# function to determine the type of card that was provided
def card_type(card_num):
card_num = str(card_num)
AMEX = ["34", "37"]
MASTERCARD = ["51", "52", "53", "54", "55"]
VISA = ["4"]
if (card_num[0:2]) in AMEX:
print("AMEX")
elif (card_num[0:2]) in MASTERCARD:
print("MASTERCARD")
elif (card_num[0]) == VISA[0]:
print("VISA\n")
else:
print("INVALID")
# main program to run all the above created functions
def main():
#get input from user
card_num = int(input("CARD: "))
#check if the bellow 2 functions are True and if so, run the card type function so we can see what type of card was usde(visa, mastercard,amex)
if check_length(card_num):
card_type(card_num)
else:
if check_last_digit(card_num):
card_type(card_num)
main()
It looks like in your main function
#check if the bellow 2 functions are True and if so, run the card type function so we can see what type of card was usde(visa, mastercard,amex)
if check_length(card_num):
card_type(card_num)
else:
if check_last_digit(card_num):
card_type(card_num)
is supposed to check that both check_length and check_last_digit are passed. However, in your code, if check_length returns True, then the second check is not ran. You need to change your code to make sure that both test are run:
def main():
#get input from user
card_num = int(input("CARD: "))
#check if the bellow 2 functions are True and if so, run the card type function so we can see what type of card was usde(visa, mastercard,amex)
if check_length(card_num) and check_last_digit(card_num):
card_type(card_num)
else:
print("INVALID")
Edit:
There are two other errors in your implementation of the Luhn algorithm.
The odd_sum function is supposed to sum every other digit, starting from the right-most one, and skipping one, but your implementation sums the wrong digits if the number of digits of the input number is odd. To correct for that, you should, for instance, reverse the list first:
l = [int(item) * 2 for item in num[::-1]]
then, remove the first digit (the rightmost one)
l = l[1:]
and finally, take every other digit:
my_list_digits = l[::2]
Then, there's a similar error in even_sum, you should also consider reversing the list, to make sure to consider the correct digits:
my_list_digits1 = [int(item) for item in num[::-1]]
return sum(my_list_digits1)
Lastly, as Jakob mentioned, you should return False instead of "INVALID" in your check_length function.
As a refactoring tip, if you see yourself writing
if condition:
return True
else:
return False
then you can refactor that in the cleaner:
return condition
So for instance:
def check_last_digit(num):
odd = odd_sum(num)
even = even_sum(num)
return (odd + even) % 10 == 0:

How to loop a function def in python until I write the number 0

I'm trying to do a def function and have it add the digits of any number entered and stop when I type the number "0", for example:
Enter the number: 25
Sum of digits: 7
Enter the number: 38
Sum of digits: 11
Enter the number: 0
loop finished
I have created the code for the sum of digits of the entered number, but when the program finishes adding, the cycle is over, but what I am looking for is to ask again for another number until finally when I enter the number "0" the cycle ends :(
This is my code:
def sum_dig():
s=0
num = int(input("Enter a number: "))
while num != 0 and num>0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
if num>0:
return num
sum_dig()
Use list() to break the input number (as a string) into a list of digits, and sum them using a list comprehension. Use while True to make an infinite loop, and exit it using return. Print the sum of digits using f-strings or formatted string literals:
def sum_dig():
while True:
num = input("Enter a number: ")
if int(num) <= 0:
return
s = sum([int(d) for d in list(num)])
print(f'The sum of the digits is: {s}')
sum_dig()
In order to get continuous input, you can use while True and add your condition of break which is if num == 0 in this case.
def sum_dig():
while True:
s = 0
num = int(input("Enter a number: "))
# Break condition
if num == 0:
print('loop finished')
break
while num > 0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
sum_dig()
A better approach would be to have sum_dig take in the number for which you want to sum the digits as a parameter, and then have a while loop that takes care of getting the user input, converting it to a number, and calling the sum_digit function.
def sum_dig(num): # takes in the number as a parameter (assumed to be non-zero)
s=0
while num > 0: # equivalent to num != 0 and num > 0
r = num % 10
s = s + r
num = num // 10
return s
while True:
num = int(input("Enter a number: "))
if num == 0:
break
print("The sum of the digits is: " + sum_dig(num))
This enables your code to adhere to the Single-Responsibility Principle, wherein each unit of code has a single responsibility. Here, the function is responsible for taking an input number and returning the sum of its digits (as indicated by its name), and the loop is responsible for continuously reading in user input, casting it, checking that it is not the exit value (0), and then calling the processing function on the input and printing its output.
Rustam Garayev's answer surely solves the problem but as an alternative (since I thought that you were also trying to create it in a recursive way), consider this very similar (recursive) version:
def sum_dig():
s=0
num = int(input("Enter a number: "))
if not num: # == 0
return num
while num>0:
r= num %10
s= s+r
num= num//10
print("The sum of the digits is:",s)
sum_dig()

Decimals to binary in Python

I'm trying to use a function (dec2bin()) to convert decimal numbers to binary. I see the input number being printed as binary but in the wrong order. What do I need to change? Or do I need to start over?
Here is the code with the function at first then the program:
def dec2bin(value):
if value > 1:
dec2bin(value//2)
print (value%2, end = '')
invalue_ok = False
invalue = 0
while invalue_ok is False:
invalue = int(input("Give a value: "))
if invalue > 65535:
print ("Wrong. Number too big. Try again.")
elif invalue < 0:
print ("Wrong. Can only handle positive numbers.")
if invalue < 256:
print ("Number", invalue, "fits in one byte and in binary is ", dec2bin(invalue))
else:
print ("Number", invalue, "fits in 16 bytes and in binary is", dec2bin(invalue))`
The output looks like this:
Give a value: 234
1101010Number 234 fits in one byte and in binary is None
What can I do to get it right?
it works with
if value>0:
it's in the good order
There are three easier ways to do it:
The format method:
binary = "{0:b}".format(*number*)
The bin method (this also works with negative numbers):
binary = bin(*number*)
Or a function from this thread:
def intToBin(n):
if(n < 0):
return -1
elif(n == 0):
return str(n)
else:
result = ""
while(n != 0):
result += str(n%2)
n //= 2
return result[::-1]
binary = intToBin(*number*)

Python Program to check if a number is armstrong or not is not working, what am I doing wrong?

n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)

function that reverses digits, takes into consideration the sign

I've looked on the site to try and figure out how to do this but I'm still stuck.
My function is supposed to reverse digits, so reverse_digits(8765) returns 5678. This is easily done by :
def reverse_digits(num):
return int(str(num)[::-1])
However, my code needs to 1) test if it is a negative and keep it negative (so -8765 returns -5678) and 2) I think I should test to see if num is actually an int.
So far I have
def reverse_digits(num):
num = str(num)[::-1]
if num == '-':
minus = 1
num = num[:-1]
else:
minus = 0
int(num)
if minus == 1:
num = num*-1
else:
num = num
return num
It works for digits without a '-', but returns '' when it has a '-'.
I was originally trying to put the test to see if it is an int at the beginning od the loop like
if (num != int):
print("wrong type")
sys.exit()
else:
(the rest of my above code)
but that wouldn't work for me. Should I put all the code in a while loop so I can use continue/break?
Thanks!
Just don't put the - into the reversed string:
def reverse_digits(num):
return (-1 if num<0 else 1) * int(str(abs(num))[::-1])
Try to use the isdigit() string method.
def reverse_digit(num):
num_str = str(num)[::-1].strip('-')
if not num_str.isdigit():
<do what u want>
if num < 0:
return -int(num_str)
else:
return int(num_str)

Categories

Resources