function that reverses digits, takes into consideration the sign - python

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)

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:

while function with the in operator not working

gone = []
turn = 0
def play(XO,player):
while 0 == 0:
num = input("\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
while ((str(num).isdigit() == False) or ((int(num) <= 9 and int(num) >= 1) == False)) or (num in gone):
num = input("\nValue was not an available number.\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
So, in the second while loop I'm having a problem. You see the (num in gone) part? I'm trying to make it so if num is found in the gone list then it will be true, but it isn't working. Instead it passes through it.
I've tested to see if (not num in gone) applies the opposite effect, and it does!
If you need to see my entire code I can post it... btw this is for a Tic-Tac-Toe program I am making.
You're putting too much logic in one condition. Splitting it up will help you a lot.
Try something like this:
gone = []
turn = 0
def play(XO, player):
while True:
num = input(
f"\n{player} enter an available number "
f"where you want to put an '{XO}'.\n > "
)
try:
num = int(num)
except ValueError:
print("Not a valid number, try again")
continue
if num < 1 or num > 9:
print("Number not in correct range, try again")
continue
if num in gone:
print("Number already gone, try again")
continue
gone.append(num)
turn += 1

Asterisk Triangle in Python (using recursion)

I have seen multiple "python asterisk triangles" and their solutions, but I am stuck on creating an asterisk triangle using recursion (without a loop, which would make it much easier in my opinion.) Below is the current code I have:
def main():
num = int(input("Enter an integer: "))
triangle = draw_triangle(num)
print(triangle)
def draw_triangle(n):
if n == 0:
return
else:
return ("*" * n + '\n') + draw_triangle(n - 1)
main()
When I run the code, I receive "TypeError: must be str, not NoneType." I have done some research and still do not completely understand what this error is telling me. I apologize if this question was asked before, I was unable to find one dealing with any recursive functions. Thank you.
return to return ""
Input: 5
Output:
*****
****
***
**
*
This error occurs because you return a blank value. Try returning a blank string instead
Solution:
In line 9:
replace return with return ''
The code is working properly but there is just a slight problem.
When testing with base case i.e. if n == 0: the return must be set to something, if not it will return None. Thus after the input number reaches 0 it returns None anything that returns None is interpreted as a failed case in python so
Here is a work around:
def draw_triangle(n):
if n == 0:
return ''
else:
return ("*" * n + '\n') + draw_triangle(n - 1)
def main():
num = int(input("Enter an integer: "))
triangle = draw_triangle(num)
print(triangle)
main()
Thus after reaching n == 0 case the program will return a blank string and continue.

Python: Decimal to Binary

I'm trying to get the function to work, it is suppose to convert Decimal to Binary but all it gives me different numbers instead. Like if I enter 12, it would give me 2. I'm not sure where in the code my issue is located. Any help would be great, thank you!
def decimalToBinary(value):
if value < 0: #Base case if number is a negative
return 'Not positive'
elif value == 0: #Base case if number is zero
return 0
else:
return decimalToBinary(value//2) + (value%2)
This may also work
def DecimalToBinary(number):
#This function uses recursion to convert & print decimal to binary number
if number > 1:
convertToBinary(number//2)
print(number % 2,end = '')
# decimal number
decimal = 34
convertToBinary(decimal)
#..........................................
#it will show output as 110100
You faced error because you adding numbers and not iterables but want to get bits sequences...,so you have to convert values you are adding to tuples or strings (or lists), see code below:
def decimalToBinary(value):
if value < 0: #Base case if number is a negative
return 'Not positive'
elif value == 0: #Base case if number is zero
return (0,)
else:
return decimalToBinary(value//2) + (value%2,)
print decimalToBinary(12)
I've replaced (value%2) to (value%2,) to create tuple(, matter, for python it's mean creating a tuple, braces aren't do it... ) and return 0 to return (0,). However you can convert it to string too. For that replace (value%2) to str(value%2 and 0 to str(0).
Note that you can use built-int bin function ti get binary decimal:
print bin(12) # 'ob1100'
Good luck in your practice !
What about bin?
>>> bin(12)
'0b1100'
>>> bin(0)
'0b0'
>>> bin(-1)
'-0b1'
You should use bin(), a built-in python function
https://docs.python.org/3.1/library/functions.html#bin
Your problem is that you're adding up the digits of your result in decimal. So if your result was going to be 01100, your function is outputting 0+1+1+0+0 which is equal to 2. If you want your digits to stack up, then convert your results to string and concatenate:
def decimalToBinary(value):
if value < 0: #Base case if number is a negative
return 'Not positive'
elif value == 0: #Base case if number is zero
return 0
else:
return str(decimalToBinary(value//2)) + str((value%2))
print decimalToBinary(12) # prints '01100
I am assuming you're doing this for practice, and that you're aware of python's built in function bin() that already does that for you.
As an exercice, two way :
with strings:
def decimalToBinary(value):
if value < 0: #Base case if number is a negative
return 'Not positive'
elif value == 0: #Base case if number is zero
return ''
else:
return decimalToBinary(value//2) + str(value%2)
with ints:
def decimalToBinary(value):
if value < 0: #Base case if number is a negative
return 'Not positive'
elif value == 0: #Base case if number is zero
return 0
else:
return 10*decimalToBinary(value//2) + value%2
In this case, you obtain a decimal whose digits are only 1 or 0.
I would take another aproach:
def decimalToBinary(number):
if number<0:
return 'Not positive'
i = 0
result = ''
while number>>i:
result = ('1' if number>>i&1 else '0') + result
i += 1
return result

Using Python, reverse an integer, and tell if palindrome

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"

Categories

Resources