Basically, I'm trying to solve this Leetcode problem about detecting palindromes (numbers that can be read the same back and forth,) but it seems that my program detects -121 as a valid palindrome and that 10 is also a palindrome, even though for the former I have a conditional that explicitly automatically returns False for negative numbers, and that the other conditional I wrote such that it should detect 10 as not a palindrome. Can someone offer some insight to where I went wrong? Here's my code:
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
L=[]
n=0
a=str(x)
if x < 0:
print("False")
else:
for z in a:
L.append(int(z))
while n < len(L):
b=(-1*n)-1
if L[n] == L[b] and n == (len(L)/2)-1:
return("True")
print("True")
break
elif L[n] == L[b]:
n = n+1
elif L[n] != L[b]:
return("False")
print("False")
break
else:
return("False")
print("False")
break
I'm just taking this directly from the box where you write the code in on Leetcode, so that explains the top stuff.
Hey, everyone! Thanks for helping me out. It seemed that changing the strings to Booleans did help out a lot, despite Leetcode accepting the strings anyways. I added in a caveat that automatically detects numbers of length one digit to be automatically true (as when it goes to else, the division rounds down and things get messy), and Leetcode accepted it! So, thank you all so much. Also, I'll make sure next time to make sure my code is indented properly.
It is possible to check numeric palindromes without converting to strings:
def numPalindrome(N):
left,right = N,0
while left>right:
left,digit = divmod(left,10)
if left and left == right: return True # odd size palindrome
right = right*10 + digit
return left and left == right # even size palindrome
This works by forming a left and right part and comparing them for equality. The right part is formed progressively using the last digit of the left part. If, at any point the two parts are equal, we have a palindrome.
Instead of print("True"), you can directly return True
Here is a simple Palindrome() function
x = 123131 # some number
str(x) == str(x)[::-1] # compare it with its reversed
Related
This question already has answers here:
Checking odd/even numbers and changing outputs on number size
(19 answers)
Closed 8 years ago.
I'm trying to make a program which checks if a word is a palindrome and I've gotten so far and it works with words that have an even amount of numbers. I know how to make it do something if the amount of letters is odd but I just don't know how to find out if a number is odd. Is there any simple way to find if a number is odd or even?
Just for reference, this is my code:
a = 0
while a == 0:
print("\n \n" * 100)
print("Please enter a word to check if it is a palindrome: ")
word = input("?: ")
wordLength = int(len(word))
finalWordLength = int(wordLength / 2)
firstHalf = word[:finalWordLength]
secondHalf = word[finalWordLength + 1:]
secondHalf = secondHalf[::-1]
print(firstHalf)
print(secondHalf)
if firstHalf == secondHalf:
print("This is a palindrom")
else:
print("This is not a palindrom")
print("Press enter to restart")
input()
if num % 2 == 0:
pass # Even
else:
pass # Odd
The % sign is like division only it checks for the remainder, so if the number divided by 2 has a remainder of 0 it's even otherwise odd.
Or reverse them for a little speed improvement, since any number above 0 is also considered "True" you can skip needing to do any equality check:
if num % 2:
pass # Odd
else:
pass # Even
Similarly to other languages, the fastest "modulo 2" (odd/even) operation is done using the bitwise and operator:
if x & 1:
return 'odd'
else:
return 'even'
Using Bitwise AND operator
The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.
If a number is odd & (bitwise AND) of the Number by 1 will be 1, because the last bit would already be set. Otherwise it will give 0 as output.
It shouldn't matter if the word has an even or odd amount fo letters:
def is_palindrome(word):
if word == word[::-1]:
return True
else:
return False
One of the simplest ways is to use de modulus operator %. If n % 2 == 0, then your number is even.
Hope it helps,
Use the modulo operator:
if wordLength % 2 == 0:
print "wordLength is even"
else:
print "wordLength is odd"
For your problem, the simplest is to check if the word is equal to its reversed brother. You can do that with word[::-1], which create the list from word by taking every character from the end to the start:
def is_palindrome(word):
return word == word[::-1]
The middle letter of an odd-length word is irrelevant in determining whether the word is a palindrome. Just ignore it.
Hint: all you need is a slight tweak to the following line to make this work for all word lengths:
secondHalf = word[finalWordLength + 1:]
P.S. If you insist on handling the two cases separately, if len(word) % 2: ... would tell you that the word has an odd number of characters.
My code is a PYTHON program that identifies if a number is prime or not. When I entered 45 however, it said that 45 was a prime, even though 45 isn't a prime number. Also, every time I run the program, it prints 'Sorry, the number you have entered is not prime.' or 'The number is indeed prime!' multiple times, instead of once. How do I make it print the output statements once and how can fix the program so that it says 45 IS NOT a prime number.
n = eval(input("Enter a number to find if that number is prime: "))
a = 2
while n > a:
if ((n % a) == 0) & (a != n):
print('Sorry, the number you have entered is not prime.')
break
else:
print('The number you have entered is indeed prime!')
Because you are printing it every time. If you want to break after finding/not finding the prime number, indent one more level for the break.
Also, this does not calculate prime numbers. It calculates if its even number.
Follow the solution here
Your code has some issues. To start with, you're never updating a, so you only ever check if the number n is even.
Once you fix that, you have two indentation problems. The first is that the break line needs to be inside the body of the if statement. Indent it more so that it's inside the if block.
The second indentation issue is more subtle. If you leave the else where it is, it will print out that the number is prime every time you test a potential factor that doesn't divide the number. That's both unhelpful (since it prints a lot) and wrong (since it says the number is prime even if it will later find a factor and say it's not prime). You can fix this by unindenting the else line so that it is lined up with the while statement. Using an else after a loop is an obscure bit of Python syntax. The body of the else only runs if the condition of the loop fails. It gets skipped if the loop exits due to a break statement.
Here's all of those necessary fixes together:
while n > a:
if ((n % a) == 0) & (a != n):
print('Sorry, the number you have entered is not prime.')
break # indent this line more!
a += 1 # increment a, so you don't keep checking 2 over and over
else: # unindent this line (and the next line too)
print('The number you have entered is indeed prime!')
There are some other things that could be improved in your code, though they aren't causing it to run incorrectly. I'd recommend using int instead of eval to parse your number, and I'd use the logical-and operator and instead of the bitwise-and operator & in the if statement (though actually you don't need either, since the a != n check is redundant, as the loop would have already ended if it was true).
I am really sorry for the vague title but I don't really know the specifics of what's happening with my code. I am currently learning Python and finding it interesting so far. I am practicing the concept of generator functions and wrote a little program that finds palindromes using a generator function.
Here is the code (Python 3.6, written in Spyder):
def ispalindrome(n):
#creates a list for storing the element of the number one by one
l=[]
#storing the digits
while n!=0:
l.append(n%10)
n=int(n/10)
#setting useful variables
i=len(l)-1
flag=False
#traversing the list and checking whether palindrome
for n in range(0,len(l)):
#this block is executed only if n is less than (len(l)-1)-n
if n<i-n:
#comparing elements
if l[n]==l[i-n]:
#flag is set to true everytime l[n] equals l[(len(l)-1)-n]
flag=True
else:
break
#if n>(len(l)-1)-n
else:
break
#returns the flag
return flag
#basic generator function that yields whenever ispalindrome() returns true
def palindromes(n=1111):
while True:
if ispalindrome(n): yield n
n+=1
#traversing through palindromes generator function
for n in palindromes():
if n>1131: break
print('{} is a palindrome'.format(n))
When ran I get this output:
1111 is a palindrome
1121 is a palindrome
1131 is a palindrome
Needless to say the output is completely wrong. I added a few prints in my code and tried to find out the issue and it looks like the program is exiting the for loop inside ispalindrome() function early. It is exiting the for-loop as soon as it encounters two digits and two ends which match, when this should not be the case. Is it because of the break keyword somehow?
I will greatly appreciate if someone can point out what am I doing wrong with this code and how should I approach this correct the issue. Thanks in advance!
I think your problem is that you've got the idea backwards.
With the current format of your code you should be assuming it IS a palindrome and breaking when you discover it is not.
Instead you are assuming it is not, then setting it to "it is" the first time you see equality. But then the next time you see inequality you merely break without setting it to false again.
If I were to code this I wouldn't bother with a flag, I would merely return "false" the moment an inequality was found.
Your logic isn't right.
By default, you think the number is not a palindrome (flag=False), and if you see a mirrored int, you set the flag to true (if l[n]==l[i-n]: flag=True).
You should do the contrary. You should set the flag to True by default, and if an item is not mirrored, return a flag to False.
As pointed out by the fellow users, my code was clearly logically in the wrong. I was never setting back flag variable to False whenever I was exiting from the for loop. So I took in account the suggestions made and changed my code.
Here is the code following my previous solution with a flag variable:
def ispalindrome(n):
#creates a list for storing the element of the number one by one
l=[]
#storing the digits
while n!=0:
l.append(n%10)
n=int(n/10)
#setting useful variables
i=len(l)-1
flag=False
#traversing the list and checking whether palindrome
for n in range(0,len(l)):
#this block is executed only if n is less than (len(l)-1)-n
if n<i-n:
#comparing elements
if l[n]==l[i-n]:
#flag is set to true everytime l[n] equals l[(len(l)-1)-n]
flag=True
else:
flag=False
break
#if n>(len(l)-1)-n
else:
break
#returns the flag
return flag
#basic generator function that yields whenever ispalindrome() returns true
def palindromes(n=1111):
while True:
if ispalindrome(n): yield n
n+=1
#traversing through palindromes generator function
for n in palindromes():
if n>2552: break
print('{} is a palindrome'.format(n))
And here is the one suggested by both Blusky and Fredman (more efficient than mine to say the least):
def ispalindrome(n):
#creates a list for storing the element of the number one by one
l=[]
#storing the digits
while n!=0:
l.append(n%10)
n=int(n/10)
#setting useful variables
i=len(l)-1
#traversing the list and checking whether palindrome
for n in range(0,len(l)):
#this block is executed only if n is less than (len(l)-1)-n
if n<i-n:
#comparing elements
if l[n]!=l[i-n]:
#flag is set to true everytime l[n] equals l[(len(l)-1)-n]
return False
#if n>(len(l)-1)-n
else:
break
#returns the flag
return True
#basic generator function that yields whenever ispalindrome() returns true
def palindromes(n=1111):
while True:
if ispalindrome(n): yield n
n+=1
#traversing through palindromes generator function
for n in palindromes():
if n>2552: break
print('{} is a palindrome'.format(n))
P.S: I am neither a professional s/w dev nor have I access to high quality courses or a mentor, that's why question boards like stackoverflow is useful for me. I know this is a dumb question and if I thoroughly checked my code again and again I might have realized the mistake, but I don't think it requires a downvote, does it?
I am currently partway through a school project which requires me to create a python program that can read in two non-negative integers, begin and end, and print out all of the palindromes which occur between begin and end (inclusive). The code we have been given is this:
begin = int(input('Enter begin: '))
end = int(input('Enter end: '))
palindromes = 0
# Add your code here. You will want to start with a "for x in range" style loop.
print('There are', palindromes, 'palindrome(s) between', begin, 'and', end)
Question: How would I calculate how many palindromes are in the range of the two numbers entered (and which numbers are palindromes)?
Research: I have tried having a look at pages, this one was a good one though I (being new to python) could not make sense of it when I put it into code:
how to check for a palindrome using python logic
Palindrome number are written in the same way from right to left and from left to right : Exemple :
123 is not a palindrome number because its inverted representation is 321
121 is a palindrome number because its inverted representation is 121
and the simpliest way to do this in python is to convert the number into a string and compare it to its inverted representation (Let's say that n is a number and we want to know if it's a palindrome or not) :
if str(n) == str(n)[::-1]:
print "It's a palindrome number"
so the solution for your problem is an if brunch inside in iteration like below :
print "Enter begin:"
begin = int(raw_input("> "))
print "Enter end:"
end = int(raw_input("> "))
palindromes = 0
for x in range(begin, end):
if str(x) == str(x)[::-1]:
palindromes += 1
print "There are %d palindrome(s) between %d and %d" % (palindromes, begin, end)
A palindrome is a number which when written reversed is same as the original number. For example, 1234321 is a palindrome.
So, to check this, all you have to do is check if the reverse of the number is the same as original.
Here's the code.
begin = int(input('Enter begin:'))
end = int(input('Enter end:'))
palindromes = 0
for i in range(begin, end+1, 1):
if str(i) == str(i)[::-1]: #Here I convert the int to string and check if t matches the reverse
palindromes += 1
print i
print "Total number of palindromes = ",palindromes
Since this is school work I don't see a huge benefit in writing code for you, but here's how to break down the problem.
As the comment in your example says, you're going to want to start with a for x in range loop. In this case I suggest you use the version of range() that takes both a start point and a stop point (begin, and end) -- note that this will iterate over numbers between start and stop INCLUDING start but NOT stop.
Example -- prints numbers 1 to 9 each on their own line:
for x in range(1, 10):
print(x)
Inside your for loop you can then test to see if x is a palindrome. If it is you'll want to add it to a list of found palindromes. Later on you can set your palindromes variable to be the length of this list, and print out the contents as needed.
To find out if x is a palindrome, the answer you've found should help. Alternatively you can think about what a palindrome is and have a go at writing your own method. You'll want to convert x to a string before you start, and then it's just a case of comparing the first and last halves of the string, and there are a few interesting ways of doing this :)
Here are two options you could try:
1) Use slicing to split the string in half (ignoring the middle character if there is an odd number of characters). Reverse ONE half of the string, and then compare it with the other half; if they are the same then it's a palindrome.
2) Use another for loop with a start of 0 and a stop of half the length (rounded down to the nearest whole number). Inside the loop take slices of both ends of the string and compare them.
Example (where x is the loop counter and currently has a value of 0).
string = 'abcd'
string[0+x]
'a'
string[-(1+x)]
'd'
For both of these answers you'll want to look at how to slice a string if you're not already familiar with this. There's some helpful examples in this Python introduction.
Thank you everyone, the code I found to be the answer was this:
begin = int(input('Enter begin: '))
end = int(input('Enter end: '))
palindromes = palindromes = len([i for i in range(begin, end+1) if str(i) == str(i)[::-1]])
for i in range(begin, end+1):
if str(i) == str(i)[::-1]:
print(i,'is a palindrome')
print('There are', palindromes, 'palindrome(s) between', begin, 'and', end)
# Palindrome Number Calculator
Palindrome = False
Test = 0
newInt = 0
myInt = int(input("Enter a number "))
myIntReversed = int(str(myInt)[::-1])
if myInt == myIntReversed:
print("Your number is a palindrome")
Palindrome = True
exit()
while Palindrome == False:
myInt += myIntReversed
Test += 1
myIntReversed = int(str(myInt)[::-1])
if myInt == myIntReversed:
print("Palindrome")
print(myInt)
Palindrome = True
exit()
If you use pycharm then you can use the debug feature to see what test number the computer is at. I am not printing this number so the program runs faster. Try to see if your program can see what the palindrome of 196 is :)
This question already has answers here:
error while passing the value in python
(2 answers)
Closed 8 years ago.
def row_minimum(x,L):
L=L
if x=='1':
row_minimum1=min(L[0],L[1],L[2],L[3],L[4])
return row_minimum1
elif x=='2':
row_minimum2=min(L[5],L[6],L[7],L[8],L[9])
return row_minimum2
elif x=='3':
row_minimum3=min(L[10],L[11],L[12],L[13],L[14])
return row_minimum3
table(L)
def user_input(y):
if y in ['1','2','3','A','B','C','D','E']:
condition = False
elif y !=['1','2','3','A','B','C','D','E']:
condition = True
while condition == True:
z=input("Enter a row (as a number) or a column (as and uppercase letter):")
if z in ['1','2','3','A','B','C','D','E']:
condition = False
return z
def menu(a,L):
if a==1:
display_table(L)
elif a==2:
x=input("Enter a row (as a number) or a column (as and uppercase letter):")
user_input(x)
print (user_input(x))
if user_input(x) in ['1','2','3']:
mini = row_minimum(x,l)
print ("2")
print("Minimum is:",row_minimum(x,L))
i am getting the value of user_input(x) to none instead i want it to take the value from the user and compare in the if statement and do the minimum.
You have a nested definition for user_input and the first one doesn't return anything, resulting in None being returned. Take out the first or second def.
Note that this is far from the only thing wrong with this program.
Looks like you have a logic issue in user_input() function. If I understood it right, you are trying to check if y is one of the row/column names and set condition to False in this case. Otherwise (if it is not in your list of allowed characters), you want to set the condition to True and re-prompt the user for correct input until she gives you the value you want.
If it is so, you better be checking y if it is NOT in the list. Your code, though, checks if y is not the LIST itself: y !=['1','2','3','A','B','C','D','E']. Even if the user gives you a good value, say 'B' it is still not equal to the list of strings ['1','2','3','A','B','C','D','E'], it is IN this list (thats what you should be checking for). I think, itll help if you rewrite the function to make it something like:
def user_input(y):
if y in ['1','2','3','A','B','C','D','E']:
condition = False
else:
condition = True
while condition == True:
z=input("Enter a row (as a number) or a column (as and uppercase letter):")
if z in ['1','2','3','A','B','C','D','E']:
condition = False
return z
You may also want to experiment with Python style guide and make this code look nicer ;)
Your user_input() function seems like a bad idea. As far as I can tell it is meant to check for bad input, and keeps asking for input until it gets good input. The problem is, it only returns if the initial input was bad, if the initial input was good, then the function does not return.
You can just get rid of this function altogether, since you end up checking the input anyway. you can just do:
def menu(a,L):
if a==1:
display_table(L)
elif a==2:
while True:
x=input("Enter a row (as a number) or a column (as and uppercase letter):")
print x
if x in ['1','2','3']:
mini = row_minimum(x,l)
print ("2")
print("Minimum is:",row_minimum(x,L))
break
elif x in ['A','B','C','D','E']:
whatever you want to do here
break