Python Palindrome - python

So my task is to see and check a positive integer if its a palindrome. I've done everything correctly but need help on the final piece. And that the task of generating a new a palindrome from the one given given by the user. Am i on the right track with the while loop or should i use something else? So the result is if you put 192 it would give back Generating a palindrome....
483
867
1635
6996
"""Checks if the given, positive number, is in fact a palindrome"""
def palindrome(N):
x = list(str(N))
if (x[:] == x[::-1]):
return True
else: return False
"""Reverses the given positive integer"""
def reverse_int(N):
r = str(N)
x = r[::-1]
return int(x)
def palindrome_generator():
recieve = int(input("Enter a positive integer. "))
if (palindrome(recieve) == True):
print(recieve, " is a palindrome!")
else:
print("Generating a palindrome...")
while palindrome(recieve) == False:
reverse_int(recieve) + recieve

If I understand your task correctly, the following should do the trick:
def reverse(num):
return num[::-1]
def is_pal(num):
return num == reverse(num)
inp = input("Enter a positive number:")
if is_pal(inp):
print("{} is a palindrome".format(inp))
else:
print("Generating...")
while not is_pal(inp):
inp = str(int(inp) + int(reverse(inp)))
print(inp)
The variable inp is always a string and only converted to int for the arithmetic.

I've been using this solution for many years now to check for palindromes of numbers and text strings.
def is_palindrome(s):
s = ''.join(e for e in str(s).replace(' ','').lower() if e.isalnum())
_len = len(s)
if _len % 2 == 0:
if s[:int(_len/2)] == s[int(_len/2):][::-1]:
return True
else:
if s[int(_len/2+1):][::-1] == s[:int(_len/2)]:
return True
return False

This one is using Complement bitwise and Logical AND and OR operators
_input = 'Abba' # _input = 1221
def isPalindrome(_):
in_str = str(_).casefold() # Convert number to string + case insensitive
for _ in range(int(len(in_str) / 2)): # Loop from 0 till halfway
if in_str[_] != in_str[~_]:
return False
return True
print(_input, isPalindrome(_input) and ' is palindrome' or ' is not palindrome')
Abba is palindrome

Related

Why does one part of conditional statements in Python returns None while others are ok?

I need to write a code that prints out valid or invalid for an input of letters and numbers for a license plate. The conditions are: first two characters must be letters, characters have to be between 2 and 6, and if numbers are used, 0 should not be the first, nor should a number appear before a letter.
I put the code below on Thonny and cannot understand why len(l) == 4 part of the conditional statement for def valid_order() returns None and does not execute the next line of the code whereas others work fine. My code should return "Valid" for CSAA50, but it returns invalid. Why?
Also, is there an elegant way to write def valid_order()?
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s[0:2].isalpha() and 6 >= len(s) >= 2 and s.isalnum() and valid_order(s):
return True
else:
return False
def valid_order(c):
n = []
l = list(c[2:len(c)])
for i in c:
if i.isdigit():
n += i
if n and n[0] == "0":
return False
if len(l) == 2:
if l[0].isdigit() and l[1].isalpha():
return False
if len(l) == 3:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha():
return False
else:
if l[1].isdigit() and l[2].isalpha():
return False
if len(l) == 4:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha() or l[3].isalpha():
return False
else:
if l[1].isdigit():
if l[2].isalpha() or l[3].isalpha():
return False
else:
if l[2].isdigit() and l[3].isalpha():
return False
else:
return True
main()

Problem in coding with function in python: Base 2 & 10 integer palindrome

There was a question which asked to write a code, to get continuous integer input from user until a negative integer is input and for each input I should evaluate if it is a palindrome in both base 10 and 2. If yes then print 'Yes' else print 'No'.
For example: 99 = (1100011)base2, both versions are palindrome so it prints 'Yes'
This is a usual elementary method.
while 1:
num = int(input('Input: '))
if num > 0:
num1 = str(num)
if num1 == num1[::-1]:
list1 = list(bin(num))
list1.pop(0)
list1.pop(0)
n = ''.join(list1)
if n == n[::-1]:
print('Yes')
else:
print('No')
else:
print('No')
else:
break
But when I tried to type a code using defining a new function it didn't work well. Here following is the code. Can you note what is wrong with this.
def palindrome(n):
n = str(n)
if n == n[::-1]:
return True
else:
return False
def b2_palindrome(n):
list1 = list(bin(n))
list1.pop(0)
list1.pop(0)
n = ''.join(list1)
palindrome(n)
while 1:
num = int(input('Input: '))
if num > 0:
if b2_palindrome(num) and palindrome(num):
print('Yes')
else:
print('No')
else:
break
#dspencer: edited the indentations
you're not returning the value of the palindrome call in b2_palindrome
see below:
def b2_palindrome(n):
list1 = list(bin(n))
list1.pop(0)
list1.pop(0)
n = ''.join(list1)
return palindrome(n) # <-- added return here

Blank List, Return False

I'm looking to write a function definition named has_evens that takes in sequence of numbers and returns True if there are any even numbers in the sequence and returns False otherwise.
My code is correct, except when it receives something empty, like "([])". I need to account for that. Here's my code:
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
elif num % 2 != 0:
return False
if ([]):
return False
The final part is a desperate attempt to account for blank lists. More formally, it needs to pass this assertion:
assert has_evens([]) == False
You should only return True when an even is found:
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
return False
Python has an any function to make this simpler:
def has_evens(s):
return any(num % 2 == 0 for num in s)
I answered my own question. I just needed to un-indent my lines
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
else:
return False

checking whether representation of number in a given base is valid

i have written this code which checks whether a number is correctly represented in a given base. for all the invalid cases it gives false but for true ones it says string index out of range.
def check(n,a,i=0):
if int(n[i])>=a :
return False
else:
return check(n,a,i+1)
n = str(input('enter no:'))
a =int(input('enter base:'))
print(check(n,a,i=0))
The pythonic way:
def is_base_x(num_string, base):
for single_char in num_string:
if int(single_char) >= int(base):
return False
return True
As #ooga pointed out, you need to check when i is larger than the length of your number, you can make it like:
def check(n,a,i=0):
if len(n) <= i:
return True
if int(n[i])>=a :
return False
else:
return check(n,a,i+1)
n = str(input('enter no:'))
a = int(input('enter base:'))
print(check(n,a,i=0))
It would be better if it could check bases above 10. Something like this:
import string
def check(num, base, i = 0):
if i >= len(num):
return True
if not num[i].isdigit():
val = string.ascii_lowercase.find(num[i].lower())
if val == -1 or val + 10 >= base:
return False
elif int(num[i]) >= base:
return False
return check(num, base, i + 1)
while True:
num = raw_input('Enter number: ')
if len(num) == 0: break # null string breaks
base = int(raw_input('Enter base: '))
print(check(num, base))

Python: trying to check for a valid phone number

I am trying to write a program that accepts a phone number in the format XXX-XXX-XXXX and translates any letters in the entry to their corresponding numbers.
Now I have this, and it will allow you to reenter the correct number if its not correct to start, but then it translates the original number entered. how do i fix this?
def main():
phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
validNumber(phone_number)
translateNumber(phone_number)
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c != '-':
phone_number=input('Please enter a valid phone number: ')
return phone_number
elif not c.isalnum():
phone_number=input('Please enter a valid phone number: ')
return phone_number
return phone_number
def translateNumber(phone_number):
s=""
for char in phone_number:
if char is '1':
x1='1'
s= s + x1
elif char is '-':
x2='-'
s= s + x2
elif char in 'ABCabc':
x3='2'
s= s + x3
elif char in 'DEFdef':
x4='3'
s= s + x4
elif char in 'GHIghi':
x5='4'
s= s + x5
elif char in 'JKLjkl':
x6='5'
s= s + x6
elif char in 'MNOmno':
x7='6'
s= s + x7
elif char in 'PQRSpqrs':
x8='7'
s= s + x8
elif char in 'TUVtuv':
x9='8'
s= s + x9
elif char in 'WXYZwxyz':
x10='9'
s= s + x10
print(s)
import re
def validNumber(phone_nuber):
pattern = re.compile("^[\dA-Z]{3}-[\dA-Z]{3}-[\dA-Z]{4}$", re.IGNORECASE)
return pattern.match(phone_nuber) is not None
If you don't want to use regular expressions: You can use isalnum to check if something is a number or letter. You can access the nth character in a string using mystr[n] so, you could try:
def validNumber(phone_number):
if len(phone_number) != 12:
return False
for i in range(12):
if i in [3,7]:
if phone_number[i] != '-':
return False
elif not phone_number[i].isalnum():
return False
return True
To see what phone_number[i] is doing, try this:
for i in range(len(phone_number)):
print i, phone_number[i]
Using enumerate:
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c != '-':
return False
elif not c.isalnum():
return False
return True
Once you have it working, you should use it later (inside of main) like:
def main():
phone_number = '' # an invalid number to initiate while loop
while not validNumber(phone_number):
phone_number = input('Please enter a phone number in the format XXX-XXX-XXXX: ')
translated_number = translateNumber(phone_number)
You should use a regex to match the text.
the string module has a translate function that will replace most of your logic
code example below. note how i cast everything into lowercase to simplify the regex and translation.
import string
import re
RE_phone = re.compile("^[a-z0-9]{3}-[a-z0-9]{3}-[a-z0-9]{4}$")
map_in = 'abcdefghijklmnprstuvwxyz'
map_out = '222333444555667778889999'
mapped = string.maketrans( map_in , map_out )
def main():
while True:
phone_number= raw_input('Please enter a phone number in the format XXX-XXX-XXXX: ')
phone_number = phone_number.lower()
if RE_phone.match(phone_number):
break
print "Error. Please try again"
print translateNumber(phone_number)
def translateNumber(phone_number):
return phone_number.translate( mapped )
main()
you can go for:-
def contact_validate(s):
try:
int(s)
return True
except ValueError:
return False
>>> print contact_validate("+12345")
True
>>> print contact_validate("75.0")
False
>>> print contact_validate("hello")
False
I think this can be helpful
def checkvalidNumber(phone_number):
T={"-":0,"+":0,"_":0}
for i in str(phone_number):
if i in list(T.keys()):
if (i=="_" or i=="-") and (T["-"]>=1 or T['_']>=1):
return False
elif i=="+" and T[i]>=1:
return False
else:
T[i]+=1
elif not i.isdigit():
return False
return True
This is a fairly pythonic way to do it in my opinion
def validNumber(phone_number):
return all([x.isdigit() for x in phone_number.split("-")])
It splits the input at "-", checks that each remaining item is a number and returns a single True or False value.
all() - returns True if bool(x) is True for all x in iterable

Categories