How to make a Palindrome Calculator in Python - python

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 :)

Related

My code will not divided the number it produces [duplicate]

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.

Write a python program to find sum of first and last digit of a number by using loop

Hello I am new to coding and just learn some basics of codding can anyone help me out with this problem :- I have written a code to find 1st and last term using loop but can't add them the code is given below
n = input("enter your number:-")
#By loop
if (n.isnumeric):
for i in range(len(n)):
if i == 0:
print(f" your first digit of the number is {n[0]}")
elif i== len(n)-1:
print(f" your last digit of the number is {n[-1]}")
else:
print("Please enter a number and try again!")
please can someone modify this code to find the sum of 1st and last digit ?
thank you:)
Actually, you're very CLose to the answer you're seeking, there are just a few errors to be corrected. See the revised version, and check?
Note - this is to follow OP's thinking, and make minimum changes.
Of course, there're many alternative ways to achieve it (and more error checking for invalid inputs, but that's another story/exercise).
n = input("enter your number:-") # ex. 123
#By loop
if (n.isnumeric()): # calling the method: isnumeric()
for i in range(len(n)):
if i == 0:
first = n[0] # assign it to first digit
print(f" your first digit of the number is {n[0]}")
elif i == len(n)-1:
last = n[len(n) -1] # assign it to last digit
print(f" your last digit of the number is {n[-1]}") # convert to integer
print(f' the sum of first and last digits: {int(first)+int(last)} ')
# 4 <- given input 123
You already know how to get the last item in a sequence - i.e., n[-1]
Therefore, using a loop is irrelevant.
What you do need to do however is to check 2 things.
Is the input at least 2 characters long?
Is the input comprised entirely of decimal characters
Which gives:
inval = input('Enter a number with at least 2 digits: ')
if len(inval) > 1 and inval.isdecimal():
first = inval[0]
last = inval[-1]
print(f'Sum of first and last digits is {int(first)+int(last)}')
else:
print('Input either too short or non-numeric')
Another interesting approach using map() and some unpacking to process the input:
inval = input('Enter a number with at least 2 digits: ')
if len(inval) > 1 and inval.isdecimal():
first, *_, last = map(int, inval)
print(f'Sum of first and last digits is {first+last}')
else:
print('Input either too short or non-numeric')

Happy Numbers doesn't update variable

I've been coding for about 3 months. Could someone help me understand why my code isn't working? I could look up the answer, but I'd really like to figure out what is going wrong. It runs perfectly the first time through the code, but while it is While-Looping, x always stays as the number inserted into the function. Thanks for your help! The assignment and code is below (for an Udemy class).
Happy Numbers -
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your output here. Find first 8 happy numbers.
def find_happy_number(x):
#we need a bunch of lists
digit_list = []
squared_list = []
result_list = []
happy_numbers = []
unhappy_numbers = []
while True:
#break our number into digits
x = str(x)
for digit in x:
digit_list.append(int(digit))
#square each digit and store in list
for digit in digit_list:
squared_digit = digit**2
squared_list.append(squared_digit)
#adds all numbers on that list
result = sum(squared_list)
print(result)
#check to see if it is a happy number
if result == 1:
print(f'{x} is a happy number!')
break
#check to see if it is an un-happy number
if result in result_list:
print(f'{x} is an UN-happy number!')
break
#if it isn't we continue the churning.
#adds result to result list to see if we are looping infinitally
x = result
result_list.append(result)
`
The PROBLEM is that you are not resetting digit_list and squared_list in every loop, so they just keep getting bigger and bigger. Move their initialization into the while loop, or use a list comprehension instead of a loop.
Consider this for your loop:
while True:
digit_list = [int(digit) for digit in str(x)]
squared_list = [digit**2 for digit in digit_list]
Now you don't need to initialize them. Or, for extra fun, combine it all into one:
while True:
result = sum(int(digit)**2 for digit in str(x))

Writing a pseudocode algorithm for GCSE

My text book asks me to "write pseudo code algorithm which inputs 10 numbers. Each time a number less than zero is input, program displays which number it is, and its value. When all numbers have been input, display the average of all the negative numbers. Your algorithm should allow for the fact that there may be no negative numbers".
The issue I have is that I'm unsure on how to write pseudo code correctly, so I've written it in python code-however, that is not necessarily the task. Furthermore, I've been able to more or less to everything but the issue where I need display the average of all the negative numbers has gotten me stuck... I'm not sure how to add that into my code and I am desperate! Need this for school tomorrow!
count = 0
nums = []
while count != 10:
num = int(input ("enter a number "))
nums.append(num)
if num < 0:
print (num)
neg_nums.append(num)
count = count+1
print (neg_nums)
I actually need to print the average of all the negative numbers, however I have no clue on how I can actually code that into this...
You almost had it. Just store only the negative numbers to the list and then in the end sum all of them up and divide by the amount of negative numbers. I also changed the loop from while loop to for loop, because it makes the code clearer and more compact:
neg_nums = []
for _ in range(10):
num = int(input("enter a number "))
if num < 0:
print(num)
neg_nums.append(num)
if neg_nums:
print(sum(neg_nums) / len(neg_nums))
else:
print("no negative numbers")
We also check in the end if there were some negative numbers inputted, so we don't end up calculating 0 / 0.

How to compare inputted numbers without storing them in list

Note: This is not my homework. Python is not taught in my college so i am doing it my myself from MITOCW.
So far i have covered while loop, input & print
Q) Write a program that asks the to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered it should print a message to the effect
How can i compare those 10 number without storing them in some list or something else? Coz i haven't covered that as if yet.
print "Enter 10 numbers: "
countingnumber=10
while countingnumber<=10:
number=raw_input():
if number % 2 == 0:
print "This is odd"
countingnumber=countingnumber+1
else:
print "This is even. Enter the odd number again"
i think the program will look something like this. But this has some unknown error & How can i compare all the numbers to get the largest odd number without storing those 10 numbers in the list.
print "Enter 10 numbers: "
countingNumber = 1
maxNumber = 0
while countingNumber<=10:
number=int(raw_input())
if (number % 2 == 0):
countingNumber = countingNumber+1
if (maxNumber < number):
maxNumber = number
else:
print "This is even. Enter the odd number again"
print "The max odd number is:", maxNumber
you can just define a maxnum variable and save the max in it! also you must use int(raw_input()) instead raw_input()
print "Enter 10 numbers: "
maxnum=0
for i in range(10):
number=int(raw_input())
if number%2 == 0:
print "This is odd"
if number>maxnum:
maxnum=number
else:
print "This is even. Enter the odd number again"
print "max odd is :{0}".format(maxnum)
DEMO:
Enter 10 numbers:
2
This is odd
4
This is odd
6
This is odd
8
This is odd
12
This is odd
14
This is odd
16
This is odd
100
This is odd
2
This is odd
4
This is odd
max odd is :100
Whenever I do input, I like to make sure I don't leave room for human error giving me bugs.
Because I put in extra checks I break code into a lot of separate function. This also gives code the quality of being non-coupled. ie) You can reuse it in other programs!!
def input_number():
while true:
input = raw_input("Enter Value: ")
if not input.isdigit():
print("Please enter numbers only!")
else:
return int(input)
Designing the input function in this fashion gives the code no opportunity to crash. We can now use it in a function to get odd numbers!
def input_odd_number():
while true:
input = input_number()
if input % 2 == 0:
print("Please enter odd numbers only!")
else:
return input
Now we can finally move onto the main code. We know we need ten numbers so lets make a for loop. We also now we need to hold onto the largest odd number, so lets make a variable to hold that value
def largest_odd(count = 10): // its always nice to make variables dynamic. The default is 10, but you can change it when calling!
max_odd = input_odd_number() // get the first odd number
for i in range(count - 1): // we already found the first one, so we need 1 less
new_odd = input_odd_number()
if new_odd > max_odd:
max_odd = new_odd
print("The largest odd value in '{}' inputs was: {}".format(count, max_odd)
In your solution are multiple flaws.
A syntax error: The colon in number=raw_input():.
raw_input returns a string and you have to cast it to an int.
Your while loop just runs one time, because you start with 10 and compare 10 <= 10. On the next iteration it will be 11 <= 10 and finishes.
Also you have mixed odd an even. even_number % 2 gives 0 and odd_number % 2 gives 1.
To get the biggest value you only need a additional variable to store it (See biggest_number in my solution). Just test if this variable is smaller then the entered.
You ask again if the number is odd, but you should take every number and test only against odd numbers.
A working solution is:
print "Enter 10 numbers"
count = 0
max_numbers = 10
biggest_number = None
while count < max_numbers:
number=int(raw_input("Enter number {0}/{1}: ".format(count + 1, max_numbers)))
if number % 2 == 1:
if biggest_number is None or number > biggest_number:
biggest_number = number
count += 1
if biggest_number is None:
print "You don't entered a odd number"
else:
print "The biggest odd number is {0}".format(biggest_number)
If you wonder what the format is doing after the string take a look in the docs. In short: It replaces {0} with the first statement in format, {1} with the second and so on.
here is the correct code for that:
print "Enter 10 numbers: "
countingnumber=1
MAX=-1
while countingnumber<=10:
number=int(raw_input())
if number%2==1:
if number>MAX:
MAX=number
if MAX==-1:
print "There Weren't Any Odd Numbers"
else:
print MAX
here are some notes about your errors:
1- you should cast the raw input into integer using int() function and the column after calling a function is not needed and therefor a syntax error
2- your while loop only iterates once because you initial counting number is 10 and after one iteration it would be bigger than 10 and the while body will be skipped.
3-an even number is a number that has no reminder when divided by 2 but you wrote it exactly opposite.
4- you don't need to print anything in the while loop, you should either print the biggest odd number or print "There Weren't Any Odd Numbers".
5- an additional variable is needed for saving the maximum odd number which is MAX.
Last note: in the code provided above you can combine the two ifs in the while loop in to one loop using 'and' but since you said you are a beginner I wrote it that way.

Categories