In response to the following task, "Create an algorithm/program that would allow a user to enter a 7 digit number and would then calculate the modulus 11 check digit. It should then show the complete 8-digit number to the user", my solution is:
number7= input("Enter a 7 digit number")
listnum= list(number7)
newnum=list(number7)
listnum[0]=int(listnum[0])*8
listnum[1]=int(listnum[1])*7
listnum[2]=int(listnum[2])*6
listnum[3]=int(listnum[3])*5
listnum[4]=int(listnum[4])*4
listnum[5]=int(listnum[5])*3
listnum[6]=int(listnum[6])*2
addednum= int(listnum[0])+int(listnum[1])+int(listnum[2])+int(listnum[3])+int(listnum[4])+int(listnum[5])+int(listnum[6])
modnum= addednum % 11
if modnum== 10:
checkdigit=X
else:
checkdigit=11-modnum
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
print(strnewnum)
(most likely not the most efficent way of doing it)
Basically, it is this: https://www.loc.gov/issn/check.html
Any help in shortening the program would be much appreciated. Thanks.
It might be worth it to do some kind of user input error checking as well.
if len(number7) != 7:
print ' error '
else:
//continue
Using a while loop for that top chunk might be a good starting point for you. Then you can sum the list and take the modulus in the same step. Not sure if you can make the rest more concise.
number7= input("Enter a 7 digit number: ")
listnum= list(number7)
newnum=list(number7)
count = 0
while count < 7:
listnum[0+count] = int(listnum[0+count])*(8-count)
count += 1
modnum= sum(listnum) % 11
if modnum== 10:
checkdigit=X
else:
checkdigit=11-modnum
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
print('New number:', strnewnum)
EDIT:
If you want it to print out in ISSN format, change your code after your if-else statement to this:
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
strnewnum = '-'.join([strnewnum[:4], strnewnum[4:]])
print('ISSN:', strnewnum)
You can convert the list to contain only int elements right after the input
number7 = int(input())
Then you can perform those operations in a loop.
for i in range(len(listnum)):
listnum[i] *= (8-i)
also the sum function does the trick of performing the addition of every element in the list (if possible)
EDIT:
addedNum = sum(listNum)
Related
The output shows a different result. Yes, the factorials of those numbers are right but the numbers outputted aren't right.
Here's the code:
input:
n = int(input("Enter a number: "))
s = 0
fact = 1
a = 1
for i in range(len(str(n))):
r = n % 10
s += r
n //= 10
while a <= s:
fact *= a
a += 1
print('The factorial of', s, 'is', fact)
Output:
Enter a number: 123
The factorial of 3 is 6
The factorial of 5 is 120
The factorial of 6 is 720
You're confusing yourself by doing it all in one logic block. The logic for finding a factorial is easy, as is the logic for parsing through strings character by character. However, it is easy to get lost in trying to keep the program "simple," as you have.
Programming is taking your problem, designing a solution, breaking that solution down into as many simple, repeatable individual logic steps as possible, and then telling the computer how to do every simple step you need, and what order they need to be done in to accomplish your goal.
Your program has 3 functions.
The first is taking in input data.
input("Give number. Now.")
The second is finding individual numbers in that input.
for character in input("Give number. Now."):
try:
int(character)
except:
pass
The third is calculating factorials for the number from step 2. I won't give an example of this.
Here is a working program, that is, in my opinion, much more readable and easier to look at than yours and others here. Edit: it also prevents a non numerical character from halting execution, as well as using only basic Python logic.
def factorialize(int_in):
int_out = int_in
int_multiplier = int_in - 1
while int_multiplier >= 1:
int_out = int_out * int_multiplier
int_multiplier -= 1
return int_out
def factorialize_multinumber_string(str_in):
for value in str_in:
print(value)
try:
print("The factorial of {} is {}".format(value, factorialize(int(value))))
except:
pass
factorialize_multinumber_string(input("Please enter a series of single digits."))
You can use map function to get every single digit from number:
n = int(input("Enter a number: "))
digits = map(int, str(n))
for i in digits:
fact = 1
a = 1
while a <= i:
fact *= a
a += 1
print('The factorial of', i, 'is', fact)
Ok, apart from the fact that you print the wrong variable, there's a bigger error. You are assuming that your digits are ever increasing, like in 123. Try your code with 321... (this is true of Karol's answer as well). And you need to handle digit zero, too
What you need is to restart the calculation of the factorial from scratch for every digit. For example:
n = '2063'
for ch in reversed(n):
x = int(ch)
if x == 0:
print(f'fact of {x} is 1')
else:
fact = 1
for k in range(2,x+1):
fact *= k
print(f'fact of {x} is {fact}')
I am relatively new to python and I have searched the web for an answer but I can't find one.
The program below asks the user for a number of inputs, and then asks them to input a list of integers of length equal to that of the number of inputs.
Then the program iterates through the list, and if the number is less than the ToyValue, and is less than the next item in the list the variable ToyValue increments by one.
NoOfToys=0
ToyValue=0
NumOfTimes=int(input("Please enter No of inputs"))
NumberList=input("Please enter Input")
NumberList=NumberList.split(" ")
print(NumberList)
for i in NumberList:
if int(i)>ToyValue:
ToyValue=int(i)
elif int(i)<ToyValue:
if int(i)<int(i[i+1]):
NoOfToys=NoOfVallys+1
ToyValue=int(i[i+1])
else:
pass
print(NoOfVallys)
Here is an example of some data and the expected output.
#Inputs
8
4 6 8 2 8 4 7 2
#Output
2
I believe I am having trouble with the line i[i+1], as I cannot get the next item in the list
I have looked at the command next() yet I don't think that it helps me in this situation.
Any help is appreciated!
You're getting mixed up between the items in the list and index values into the items. What you need to do is iterate over a range so that you're dealing solidly with index values:
NoOfToys = 0
ToyValue = 0
NumOfTimes = int(input("Please enter No of inputs"))
NumberList = input("Please enter Input")
NumberList = NumberList.split(" ")
print(NumberList)
for i in range(0, len(NumberList)):
value = int(NumberList[i])
if value > ToyValue:
ToyValue = value
elif value < ToyValue:
if (i + 1) < len(NumberList) and value < int(NumberList[i + 1]):
NoOfToys = NoOfVallys + 1
ToyValue = int(NumberList[i + 1])
else:
pass
print(NoOfVallys)
You have to be careful at the end of the list, when there is no "next item". Note the extra check on the second "if" that allows for this.
A few other observations:
You aren't using the NumOfTimes input
Your logic is not right regarding NoOfVallys and NoOfToys as NoOfVallys is never set to anything and NoOfToys is never used
For proper Python coding style, you should be using identifiers that start with lowercase letters
The "else: pass" part of your code is unnecessary
Ok, so I've got a couple issues with a program (for school again) that I'm using to add up all the digits of a number. I've got some of the program down, except 2 things. First, how to use a variable (thelength below) in replacement of a number to call a specific digit of the input (I'm not sure if this is even possible, but it would be helpful). And second, how to add up different numbers in a string. Any ideas?
Here's what I have so far:
number = str(int(input("Please type a number to add up: ")))
length = len(number)
thelength = 0
total = 0
thenumbers = []
while thelength < length:
#The issue is me trying to use thelength in the next two lines, and the fact that number is now a string
total += number[thelength]
thenumbers.append(number[thelength])
thelength += 1
for num in thenumbers:
print(num[0])
print("+")
print("___")
print(total)
Thanks for any help I can get!
I don't know what "call a specific digit of the input" means, but the error in your code is here:
total += number[thelength]
total is an int, and you're trying to add a string to it, convert the digit to an integer first.
total += int(number[thelength])
Result:
1
2
3
+
___
6
import re
import sys
INPUT_VALIDATOR = re.compile("^[0-9]+$")
input_str = input("Please type a natural number to add up: ")
if INPUT_VALIDATOR.match(input_str) is None:
print ("Your input was not a natural number (a positive whole number greater or equal to zero)!")
print ("This displeases me, goodbye puny human.")
sys.exit(1)
total = 0
for digit_str in input_str:
print(digit_str)
total += int(digit_str)
print("+")
print("___")
print(total)
If you don't need to print the digits as you go, it's even easier:
# (Add the same code as above to get and validate the input string)
print(sum(int(digit_str) for digit_str in input_str))
number = int(input("Please type a number to add up: "))
total = 0
while number > 0:
total += number % 10
total /= 10
print(total)
num % 10 pretty much gets the last digit of a number
then we divide it by 10 to truncate the number by its last digit
we can loop through the number as long as it's above 0 and take the digital sum by using the method outlined above
Every thing that you need is convert the digits to int and sum them :
>>> s='1247'
>>> sum(map(int,s))
14
But as you get the number from input it could cause a ValueErorr , for refuse that you can use a try-except :
try :
print sum(map(int,s))
except ValueErorr :
print 'please write a valin number :'
Also if you are using python 2 use raw_input for get the number or if you are using python 3 just use input because the result of both is string !
How do I add numbers in between two numbers the user inputted in Python 2.7. So a person would input 75 and 80 and I want my program to add the numbers in between those two numbers. I am very new to programming and python so any help would be awesome!
This example excludes 75 and 80. If you need to include them replace with print sum(range(n1,n2+1))
n1=input('Enter first number ')
n2=input('Enter second number ')
print sum(range(min(n1,n2)+1,max(n1,n2)))
#DSM is right!
n1=input('Enter first number ')
n2=input('Enter second number ')
print (n2-n1+1)*(n2+n1)/2
to capture user input use number1 = raw_input('Input number'). From there I'm not exactly sure what you mean from adding numbers between the two? If you want 76+77+78+79 in that example
number1 = raw_input('Input number')
number2 = raw_input('Second number')
result = 0
for n in range(int(number1)+1, int(number2)):
result+=n
print result
Here's a quick sample that should handle a few different situations. Didn't go that in-depth since I don't know the scope of the situation. Realistically you should do some form of type-checking and loop until valid input is entered. However this should get you started:
def sumNums(a, b):
total = 0
if a < b:
total = sum(range(a+1, b))
elif b < a:
total = sum(range(b+1, a))
return total
num1 = int(raw_input("First Number: "))
num2 = int(raw_input("Second Number: "))
print sumNums(num1, num2)
However I'm sure there's a more comprehensive way using lists and sum() but it seems like you only need a basic working example.
easy you just go
def add(x,y):
if True:
return add(x, y)
else:
return None
add([1,2,3,4][0], [1,2,3,4][2])
I need to make a program that the user will enter in any number and then try guess the sum of those digits.
How do i sum up the digits and then compare then to his guess?
I tried this:
userNum = raw_input("Please enter a number:\n")
userGuess = raw_input("The digits sum is:\n")
if sum(userNum, userGuess):
print"Your answer is True"
else:
print "Your answer is False"
and it didnt work
You have 2 problems here :
raw_input() doesn't return an integer, it returns a string. You can't add strings and get an int. You need to find a way to convert your strings to integers, THEN add them.
You are using sum() while using + whould be enough.
Try again, and come back with your results. Don't forget to include error messages and what you think happened.
Assuming you are new to Python and you've read the basics you would use control flow statements to compare the sum and the guess.
Not sure if this is 100% correct, feel free to edit, but it works. Coded it according to his(assuming) beginner level. This is assuming you've studied methods, while loops, raw_input, and control flow statements. Yes there are easier ways as mentioned in the comments but i doubt he's studied map Here's the code;
def sum_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
sum_digits(mynumber)
mynumber = int(raw_input("Enter a number, "))
userguess = int(raw_input("Guess the digit sum: "))
if sum_digits(mynumber) == userguess:
print "Correct"
else:
print "Wrong"
Credit to this answer for the method.
Digit sum method in Python
the python code is :
def digit_sum(n):
string = str(n)
total = 0
for value in string:
total += int(value)
return total
and the code doesnot use the API:
def digit_sum1(n):
total=0
m=0
while n:
m=n%10
total+=m
n=(n-m)/10
return total
Firstly you neet to use something such as int(raw_input("Please enter a number:\n")) so the input returns an integer.
Rather than using sum, you can just use + to get the sum of two integers. This will work now that your input is an integer.
Basically I would use a generator function for this
It will iterate over the string you get via raw_input('...') and create a list of the single integers
This list can then be summed up using sum
The generator would look like this:
sum([ int(num) for num in str(raw_input('Please enter a number:\n')) ])
Generators create lists (hence the list-brackets) of the elements prior to the for statement, so you could also take the double using:
[ 2 * int(num) for num in str(raw_input('Please enter a number:\n')) ]
[ int(num) for num in str(123) ] would result in [1,2,3]
but,
[ 2 * int(num) for num in str(123) ] would result in [2,4,6]