2016-10-17 22 views
2

ねえ、私はかなりプログラミング世界に新しいです。学校の練習問題については、私は以下のテキストを与えられました。私はこれをコードに変換すると仮定しています。私はそれに数時間を費やして、それを理解するように見えることはできませんが、私はこれを学ぶことに決めました。現在エラーが発生していますLuhnのアルゴリズムコードに擬似コード

line 7, in <module> if i % 2 == 0: TypeError: not all arguments converted during string formatting 

これはどういう意味ですか?私はまだループを学習していて、正しい形式かどうかはわかりません。御時間ありがとうございます。あなたが行うとき

1):

# GET user's credit card number 
# SET total to 0 
# LOOP backwards from the last digit to the first one at a time 
    # IF the position of the current digit is even THEN 
     # DOUBLE the value of the current digit 
     # IF the doubled value is more than 9 THEN 
      # SUM the digits of the doubled value 
     # ENDIF 
     # SUM the calculated value and the total 
    # ELSE 
     # SUM the current digit and the total 
    # ENDIF 
# END loop 
# IF total % 10 == 0 THEN 
    # SHOW Number is valid 
# ELSE 
    # SHOW number is invalid 
# ENDIF 


creditCard = input("What is your creditcard?") 
total = 0 
for i in creditCard[-1]: 
    if i % 2 == 0: 
     i = i * 2 
     if i > 9: 
      i += i 
    total = total + i 

    else: 
     total = total + i 

if total % 10 == 0: 
    print("Valid") 

else: 
    print("Invalid") 
+1

'クレジットカードが[-1]'あなたに与えます*のみ*最後の要素。 'creditCard [:: - 1]'は、代わりに 'creditCard'の逆を返します(あるいは単に' reversed(creditCard) 'を使用します)。 – Evert

+0

あなたはPython 2または3を使用していますか? 3の場合は、入力を整数に変換する必要があります –

答えて

1

まあ、私は2つの問題を見ることができます

for i in creditCard[-1] 

あなたは、単に最後の数字を取るクレジットカードに反復いけません。 あなたはおそらくこれが最初の1

2に、最後の1から数字を反復します

for i in creditCard[::-1] 

を行うためのもの) 擬似コードがない数字ならば、その位置が偶数の場合の数を倍増させると

digit_count = len(creditCard) 
for i in range(digit_count -1, -1, -1): 
    digit = creditCard[i] 

をかenumerate BUを見て:それ自体はそう、あなたがこれを行うことができさえ

ですILTイン機能

編集:

完全なサンプル:

creditCard = input("What is your creditcard?") 
total = 0 
digit_count = len(creditCard) 
for i in range(0, digit_count, -1): 
    digit = creditCard[i] 

    if i % 2 == 0: 
     digit = digit * 2 
     if digit > 9: 
      digit = digit/10 + digit % 10 # also noticed you didnt sum the digits of the number 

    total = total + digit 



if total % 10 == 0: 
    print("Valid") 

else: 
    print("Invalid") 
+0

最初の部分は完全な意味があります。第二に、どのようにそれを統合するだろうか?私はこれが何を意味するのか少し混乱しています。 – Joey

+1

私は完全なバージョンを追加しました。もう一つの修正を加えて、あなたの義務が述べたように、二倍の数値の合計を詰め込んだわけではありませんでした。youdは何度も数字を2倍にしていました(youdid 'i + = i')。それを4)にする。 10で割ると2番目の桁が得られます(これは整数なので、小数点が14/10 == 1なので)。 'digit/10 + digit%10'を実行すると、 10 'はあなたに最初の桁を与えます – DorElias

+0

ありがとうございました!私はそんなに感謝しています。 1つの最終的な質問と私はあなたを盗むのをやめますが、これは正確に '範囲(0、digit_count、-1)の意味です:' – Joey