Python ISBN program - python

I'm trying to calculate the check digit for an ISBN input on python. so far I have...
def ISBN():
numlist = []
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
**numlist == request
print numlist**
if len(request) != 10:
print "Invalid Input"
ISBN()
ISBN()
The bold bit is where im having trouble, I cant seem to split the 10 digit input into individual numbers in the list (numlist) and then multiply the seperated individual numbers by 11 then the next by 10 then the next by 9 etc...
For the next part of the program, I will need to add these new multiplied numbers in the list together, then i will use the mod(%) function to get the remainder then subtract the number from 11, any assistance with any of my coding or incorrect statements on how to calculate the ISBN would be greatly appreciated.
Thank you.

This code should get you on your way:
listofnums = [int(digit) for digit in '1234567890']
multipliers = reversed(range(2,12))
multipliednums = [a*b for a,b in zip(listofnums, multipliers)]
Strings are iterable, so if you iterate them, each element is returned as a single-character string.
int builds an int from a (valid) string.
The notation [a*b for a,b in zip(listofnums, multipliers)] is a list comprehension, a convenient syntax for mapping sequences to new lists.
As to the rest, explore them in your repl. Note that reversed returns a generator: if you want to see what is "in" it, you will need to use tuple or list to force its evaluation. This can be dangerous for infinite generators, for obvious reasons.

I believe list() is what you are looking for.
numlist=list(request)
Here is how I would write the code. I hope I'm interpreting the code correctly.
def ISBN():
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
numlist = list(request)
print numlist
else:
print "Invalid Input"
ISBN()

import itertools
if sum(x * int(d) for x, d in zip(nums, itertools.count(10, -1))) % 11 != 0:
print "no good"

Related

Python exercise about basics types, functions and plus them, changing the type of input

my python teacher ask to me to write a program that adds the digits in a 2 digit number. e.g. if the input was 35, then the output should be 3 + 5 = 8. So, a made it on this way:
two_digit_number = input("Type a two digit number: ")
print(int(two_digit_number [0] ) + int(two_digit_number [1]))
Is it wrong?
Your answer is correct but I feel like this is a better way:
number = int(input())
print(number // 10 + number % 10)
Your code is working fine and nothing wrong with it, but if you wanted to you could simplify it a little using builtins like sum and map. For instance, what map does is apply the first callable argument to an iterable passed in as the second argument (a string of characters in this case).
Here's an example using both those builtins. I also use assert to confirm once that it's a valid two digit number, because otherwise it'll work for any length number, like a five digit number.
two_digit_number = input("Type a two digit number: ")
assert len(two_digit_number) == 2, 'Enter a valid two digit number!'
print(sum(map(int, two_digit_number)))
If you wanted to, you could also rewrite it like this, using map and an assignment using implicit iterable unpacking:
two_digit_number = input("Type a two digit number: ")
first_dig, second_dig = map(int, two_digit_number)
print(first_dig + second_dig)

How to reverse a given number in python using just for loop

i did it in while loop but couldn't do it in for loop
my code using while loop :
x=int(input("enter a number: "))
i=0
while(x>0):
remainder=x%10
i=(i*10)+remainder
x//=10
print(i)
In your example your using arithmetic, but why not convert to a string to make life easier?
x = int(input("enter a number: "))
result = ""
for char in str(x)[::-1]:
result += char
print(result)
Note that [::-1] means "iterate backwards" and that if your number ends with zeros, they'll appear at the start of the reversed string. If you want, you can trim them with lstrip:
print(result.lstrip("0"))
If you remove int() then you will no need loop
x = input("enter a number: ")
result = x[::-1]
print(result)
You may need lstrip('0') to remove 0 when you convert 10 to 01 and you want to skip 0.
OR convert to int after reversing and it removes 0
x = input("enter a number: ")
result = x[::-1]
i = int(result)
print(i)
Another example - it uses for-loop but it still need str at start
x = input("enter a number: ")
i = 0
for char in reversed(x):
i = i*10 + int(char)
print(i)
With for-loop you would have to convert int to str to know how much diggits it has.
for-loop is good when you know how many items you have. while is better when you don't know how many items you have, or you don't want to work with items one-by-one but skip something, repeate it, etc.
With for-loop you could eventually use iterator/generator which will raise __StopIter__ at the end of data - but probably this iterator/generator whould have to use while for this :)

How to make a Palindrome Calculator in 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 :)

I am trying to create a program that takes a list of numbers from the user and checks whether or not the first number given in repeated in the list

i know i can use the input function in conjunction with the eval function to input a list of numbers:
numbers = eval(input("enter a list of numbers enclosed in brackets: "))
Also, given a list named items, i can get the list of all the elements of items, except the first one, with
the expression:
items[1:]
im just not sure how to go about getting the program to do what i want it to do
If you have a list and you want to know if the first value appears again later in the list, you can use:
items[0] in items[1:]
That will return True or False depending on whether the first element in items appears again later in items.
Don't use eval, ast.literal_eval is safer
import ast
numbers = ast.literal_eval(raw_input("enter a list of numbers enclosed in brackets: "))
An easier solution will be
x = l[0]
l[0] = None
print x in l
l[0] = x
The advantage is that you don't need to recreate the list
There are two parts to your problem:
get a list of numbers from the user
check if the first number is repeated in this list
There are several ways to get a list of numbers from a user. Since you seem to be new to python, I will show you the easiest way to program this:
n = raw_input("How many numbers in your list?: ")
n = int(n) # assuming the user typed in a valid integer
numbers = []
for i in range(n):
num = raw_input("enter a number: ")
num = int(num)
numbers.append(num)
# now you have a list of numbers that the user inputted. Step 1 is complete
# on to step 2
first_num = numbers[0]
for n in numbers[1:]:
if n == first_num:
print "found duplicate of the first number"
Now, there are more elegant ways to accomplish step 1. For example, you could use a list comprehension:
numbers = [int(n) for n in raw_input("Enter a bunch of space-separated numbers: ").split()]
Further, step 2 can be simplified as follows:
if numbers[0] in numbers[1:]:
print "found duplicates of the first number"
Hope this helps

ISBN check digit calculation problems

can any one offer any assistance, as to why the following code always returns the same check digit number?
def ISBN():
numlist = []
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
listofnums = [int(digit) for digit in '1234567890']
multipliers = reversed(range(2,12))
multipliednums = [a*b for a,b in zip(listofnums, multipliers)]
print multipliednums
added_result = sum(multipliednums)
print added_result
remainder = added_result % 11
print remainder
check_digit = 11 - remainder
print check_digit
ISBN()
if len(request) != 10:
print "Invalid Input"
ISBN()
ISBN()
any information or tips on how i could imptove the code, or just why it constantly eturns the same digit(9) no matter what the input.
Thank you
I think for digit in '1234567890' should be for digit in request.
Looking at your code, you can see that you accept the value of request from the user, but after checking its length, you don't do anything else with it again. There's no way the output of this program could change.
You do not seem to be calculating anything on the variable that you ask from the user.
Variable request is not used in the subsequent code...

Categories