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.
Related
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')
This question already has an answer here:
How to properly parse numbers in an arithmetic expression, differentiating positive and negative ones?
(1 answer)
Closed 3 years ago.
I am trying to make my own "calculator" though I'm getting into a problem.
When I separate the operators and the digits, negative numbers do not work.
Because the '-' symbol is counted as an operator. Now my question is how can I separate between BOTH operators and numbers including negative numbers?
I don't expect negative numbers to work with my current code, though I am trying to make them work.
Any ideas on how can I do that?
Here is the full code for the calculator.
import re
def calc(equation):
equationList = re.findall('[+-/*]|\d+', equation)
operators = [i for i in equationList if not i.isdigit()]
numbers = [i for i in equationList if i.isdigit()]
operators.insert(0,'+')
answer = 0
for i, operator in enumerate(operators):
number = numbers[i]
if operator == '+': answer += int(number)
if operator == '-': answer -= int(number)
if operator == '*': answer *= int(number)
if operator == '/': answer /= int(number)
print(f'Equation: {"".join(equationList)}\nAnswer: {answer}')
while True:
calc(input('>>> '))
When I try to run an equation with negative numbers I get an error:
>>> -5*10
Traceback (most recent call last):
File "main.py", line 22, in <module>
calc(input('>>> '))
File "main.py", line 12, in calc
number = numbers[i]
IndexError: list index out of range
So, I have a lot of information for you, but it's very relevant. I also drastically changed your code:
Easily separating the operators and the numbers will not work unless you require something such as there being parentheses/spaces around every negative number. But not only will this make it so that you cannot enter regular, unformatted equations in your calculator, it also will require you to treat negative numbers as special. Which they are, but this is not necessary. This is because you can basically ignore that they are negative. The code changes I propose will more easily let you handle any operator as well.
Any negative number can be broken down into an operation: -x is the same as 0 - x. The question is: when should the zero be added? There are two cases: when the first input is a negative sign and when there is a negative sign after another operator.
All you need to do is add some code to handle those conditions. Let us look at some examples:
>>> -2+5
3
>>> 5+-2
3
>>> (1/9)^(-1/2)
3
>>> (2+(-1))*5-2
43
The problem with negatives in your approach comes from the fact that when you separate the operators from the numbers, you do not know what should come next: an operator or a number (this is a problem for all the above examples).
One solution is to keep track of the locations of all the numbers! Doing this will allow you to know exactly how many operators are in between each number and you can figure out which numbers are negative (or where you should add a zero) through that.
I have rewritten your code for this and it is pretty different but the main idea is still there. See the code below:
import re
# Takes care of applying the operation on the left number given the right number
def applyOperation(operator, left, right):
answer = left
if operator == '(':
return NotImplemented
elif operator == ')':
return NotImplemented
elif operator == '^':
return NotImplemented
elif operator == '*': answer *= int(right)
elif operator == '/': answer /= int(right)
elif operator == '+': answer += int(right)
elif operator == '-': answer -= int(right)
else:
print("Error. Only '*', '/', '+',and '-' are allowed at the moment.")
# You could also allow a period, exponents (^), modulo, exponential, etc.
exit(1)
return answer
def calc(equation):
"""
Magical calculator (It handles negative numbers)
DISCLAIMER:
-This version does not allow parentheses or float inputs (but does allow float outputs)
-It also does not follow the order of operations
"""
numIndices = [m.span() for m in re.finditer("\d+", equation)]
prevNumber = 0
prevEnd = ''
for numIndex in numIndices:
number = float(equation[numIndex[0]:numIndex[1]])
# If at the start, just add the number
if numIndex[0] == 0:
prevNumber = number
prevEnd = numIndex[1]
continue
# Starting at the second spot of the equation is special
if numIndex[0] == 1:
# Remember this for order of operations (if implemented)
if equation[0] == "(":
# I think handling these would be best done recursively
# Or you could split on all parentheses and compute each in turn
# Or ...
return NotImplemented
# It's a negative number
elif equation[0] == "-":
prevNumber -= number
prevEnd = numIndex[1]
continue
else:
print("Error. Only numbers, '-' and '(' are allowed at the "
+"beginning of the equation.")
# You could allow a period as well.
exit(1)
# If reached here, then should have passed the first number
# Extract relevant operators and remove any spaces
operators = equation[prevEnd:numIndex[0]]
operators = "".join(operators.split())
if len(operators) == 1:
prevNumber = applyOperation(operators[0], prevNumber, number)
elif len(operators) == 2:
if (operators[1] == '-'):
prevNumber = applyOperation(operators[0], prevNumber, -number)
else:
print("Error. Currently, the second operator must always be a '-'.")
exit(1)
# If it reaches here, then parentheses are probably involved
# or syntax is probably incorrect
else:
print("Error. Only two operators are currently allowed between numbers."
+ " The second one always being a '-'.")
# You could allow all sorts of nesting with parentheses if you want.
exit(1)
prevEnd = numIndex[1]
# Do not display the decimal places if they are all 0
prevNumber = int(prevNumber) if prevNumber-int(prevNumber) == 0 else prevNumber
print("Equation:", equation,"\nAnswer:",prevNumber)
while True:
calc(input('>>> '))
Calculators are not a joke! xD
P.S. It also accepts equations of just letters.
https://www.youtube.com/watch?v=kC6YObu61_w
After watching the linked video "7 and Happy Numbers", I decided to write up a bit of code to check whether or not the given number is a happy number.
c = []
num = int(input("What number would you like to check? "))
def happyNum(n):
newNum = 0
c = []
a = str(n)
for b in a:
c.append(int(b))
for d in c:
newNum = newNum + d**2
if newNum <= 1:
return True
elif newNum == 145:
return False
elif newNum == 113:
return False
elif newNum == 130:
return False
else:
happyNum(newNum)
if happyNum(num) == True:
print("You've found yourself a happy number!")
elif happyNum(num) == False:
print("Not a happy number I'm afraid!")
I tested it with 7, which I knew from the video is a lucky number, and found that nothing was printed. I did a few tests, and the function works fine. Once it reaches 1, it enters the if statement. The only problem is that it never returns True. Why is this happening, and how can I fix it? By the way, incase this might be significant, the function is recursive.
The video is incomplete in its description of happy numbers. Numbers that are happy will wind up at 1 but they don't say what happens with unhappy numbers. If they are unhappy, they will eventually cycle through a series of numbers. So to detect if they are unhappy, you have to keep track of the numbers produced and see if you get any repeats. (Presumably what you had c = [] for but didn't use in the end.) This means you need to pass a growing set along in your recursive calls. The numbers 145, 113 and 130 aren't generally useful and shouldn't be in your code.
Here's a rework that addresses the above issues:
def is_happy(number, seen=None):
if number == 1: # it's happy
return True
if seen is None:
seen = set()
if number in seen: # a cycle, it's unhappy
return False
seen.add(number)
# separate the digits into a list; several ways to do this
digits = [ord(digit) - ord('0') for digit in str(number)]
number = 0 # we can reuse number as we got what we needed
for digit in digits:
number += digit ** 2
return is_happy(number, seen) # this could have also been a loop
number = int(input("What number would you like to check? "))
if is_happy(number):
print("You've found yourself a happy number!")
else:
print("Not a happy number I'm afraid!")
But, if we find a happy number, then all the numbers we checked in the process of determing that it is happy, are themselves happy. Ditto for unhappy numbers. So if we add some caching, using dangerous default values that carry through to subsequent calls:
def is_happy(number, seen=None, happy=set([1]), unhappy=set()):
if seen is None:
seen = set()
if number in happy: # it's happy
happy.update(seen) # all seen numbers are happy too
return True
if number in unhappy or number in seen: # a cycle, it's unhappy
unhappy.update(seen) # all seen numbers are unhappy too
return False
seen.add(number)
# separate the digits into a list; several ways to do this
digits = [ord(digit) - ord('0') for digit in str(number)]
number = 0 # we can reuse number as we got what we needed
for digit in digits:
number += digit ** 2
return is_happy(number, seen) # this could have also been a loop
for number in range(1, 1000001):
if is_happy(number):
print(number, end=" ")
print()
We can determine the happiness of numbers up to a million in 1/6 of the time than if we hadn't kept track of previous happy and unhappy numbers!
you can see my code in below. I got error that in that line "print(str(values))"
it says
Unindent doesn't match any outer indentation level.
What is wrong with it?
values = ''
def reverse(numbers):
print('please enter a 3 digit number :')
number = input()
if 100 > number:
print('the number is not 3 digit')
values[0] == number[2]
values[1] == number[1]
values[2] == number[0]
print(str(values))
print(reverse(135))
Check the print line, you've extra space before print command. After that a better way to reverse strings or numbers is using the list comprehention (you should convert your number to string first), you can make something like this:
my_value = '123' # or str(my_value)[::-1]
print my_value[::-1] # This result is 321
Note: Your if block haven't any effect, because you print the message but in the next line you proceed with operation. In this case I think that your operation should be in a else block.
This is a program to reverse a 3 digit number.
l=list(input("please enter a 3 digit no.="))
print(l[2],l[1],l[0])
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 :)