简体   繁体   中英

Need help shortening program (python beginner)

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

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)

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM