0

Pythonモジュロ関数が正しく機能していることを確認できないようです。さまざまな数値を試しましたが、正しい除算が得られないようです。

ISBN番号

print """
Welcome to the ISBN checker,

To use this program you will enter a 10 digit number to be converted to an International Standard Book Number

"""

ISBNNo = raw_input("please enter a ten digit number of choice") 


counter = 11 #Set the counter to 11 as we multiply by 11 first
acc = 0 #Set the accumulator to 0

ループを開始し、文字列の各桁に減分カウンターを掛けます 各配置を取得するには、数値を文字列として扱う必要があります

for i in ISBNNo: 
    print str(i) + " * " + str(counter)
    acc = acc + (int(i) * counter) #cast value a integer and multiply by counter
    counter -= 1 #decrement counter
print "Total = " + str(acc)                   

Mod を 11 で割る (割って余りを取る)

acc = acc % 11
print "Mod by 11 = " + str(acc)

11から取る

acc = 11 - acc
print "subtract the remainder from 9 = " + str(acc)

文字列と連結する

ISBNNo = ISBNNo + str(acc)
print "ISBN Number including check digit is: " + ISBNNo
4

1 に答える 1

0

いくつかの問題を除いて、コードはほとんど正しいです。

1) ISBN の場合、チェックサム (最後の桁) を計算しようとしています。これは、9 桁のみを考慮する必要があることを意味します。

ISBNNo = raw_input("please enter a ten digit number of choice") 
assert len(ISBNNo) == 10, "ten digit ISBN number is expected"
# ...
for i in ISBNNo[0:9]: # iterate only over positions 0..9 
    # ...

2)また、ここには特別なケースがあるはずです:

ISBNNo = ISBNNo + str(acc)
print "ISBN Number including check digit is: " + ISBNNo

モジュロ 11 を実行しているため、acc は 10 に等しくなる可能性があります。ISBN では、この場合、最後の「数字」として「X」を使用する必要があり、次のように記述できます。

ISBNNo = ISBNNo + (str(acc) if acc < 10 else 'X')

ウィキペディアの例の番号を含む固定コードは次のとおりです: http://ideone.com/DaWl6y


コメントへの対応

>>> 255 // 11               # Floor division (rounded down)
23
>>> 255 - (255//11)*11      # Remainder (manually)
2
>>> 255 % 11                # Remainder (operator %)
2

(注: 私はこれを使用し//ています。これは床除算の略です。Python 2 では、/整数を除算しているため、単純にあまりにも使用できます。Python 3 では、/常に真の除算であり、//床除算です。)

于 2013-04-21T17:26:04.260 に答える