2

n数値の文字列になる変数を含む関数を定義しようとしています。nたとえば"3884892993"、関数の定義はとして始まりますがis_true(n)、nが文字列になる場合はis_true(n)、文字列を定義すると、次のようになります。などの文字列の例を使用して関数をテストしますn = "3884892993"is_true(n)ただし、使用すると構文エラーが発生します。そして、nの文字列の例を使用して、この関数をどのようにテストするのか疑問に思っています。

定義する私の関数全体をここに示します:http://oi44.tinypic.com/282i3qo.jpgしかし、私は絶対的な初心者なので、おそらく多くの間違いがあることを覚えておいてください。可能な限り:)

def is_valid("n"): #n is the number to be checked.
    number = 
    [int(y) for y in A] #converts the string into a list of useable digits.
    altern1 = integer[-2::-2] #sets altern1 as one set of alternating digits.
    double = [x*2 for x in altern1] #doubles each element of the list altern1.
    sum1 = sum(double) # adds together all the doubled items of the list.
    altern2 = integer[-1::-2] #sets altern2 as the other set of alternating digits.
    return sum2 = sum(altern2)#sums the other set of alternating digits.
    sumtotal = sum1 + sum2 #works out the total sum to be worked with.
    for mod = sumtotal % 10: #works out remainder when sumtotal is divided by 10
        if mod == 0 : #if remainder is zero sumtotal is a multiple of 10
            print 'True' #sumtotal is a multiple of 10 therefore n is a credit card number
        else:
            print 'False' #sumtotal is NOT a multiple of 10 therefore not a valid credit card number

実際の質問は次のとおりです。

数値を検証するためのアルゴリズムは次のとおりです。(a)最後から2番目の桁から始めて、最初の桁に向かって、各交互の桁を2倍にします。(b)2桁を合計し、13を1 + 3などとして扱い、その結果を2桁の合計に加算します。(c)合計が10で割り切れる場合、その数値は有効なクレジットカード番号です。

クレジットカード番号を文字列として引数として取り(たとえば、valid( "49927398716"))、その番号が有効なクレジットカード番号であるかどうかに応じてTrueまたはFalseを返す関数is_valid()を記述してテストします。

4

6 に答える 6

4

引用符は文字列リテラルにのみ使用されます。変数またはパラメータ名を引用符で囲んで、文字列になることを示すことはありません。関数定義は次のようになります。

def is_true(n):

次に、関数の本体でn、呼び出し元から渡された値を参照するために使用します。

特定の値で関数を呼び出すには、次のようにします。

is_true("3884892993")

副次的な提案:関数と変数のより説明的な名前を考えてください。たとえば、あなたの関数は合理的に呼ばれているようis_valid_card_numberです。

于 2011-10-26T21:02:57.523 に答える
1

あなたの質問が何であるかはわかりませんが、あなたがしようとしている場合:

  • 関数を正しく定義します。
    • インデントに注意してください(これはPythonで必要です!)、
    • 関数定義の例については、ここを参照してください。
  • 文字列変数を整数に変換するには、次のようにします。

    new_var = int(old_var)
    

    他の動的型付け言語とは異なり、文字列は動的に数値に変換されないため、通常は型に注意してください。明示的に行う必要があります。

  • 名前に基づいて、変数の値を読み取ります。

    my_var = vars().get('variable_name')
    

    (ここvariable_nameで、は変数の名前であり、オプションで、後の括弧内にコンテキストを指定できますvars-詳細help(vars)についてはを参照してください)

上記のいずれかで問題は解決しましたか?

編集(説明に基づく):

これで問題が解決するはずです。

def is_true(my_variable):
    # Here the variable named "my_variable" is accessible

渡された変数に対して「インプレース」で何かを実行したい場合は、悪いニュースがあります。Pythonでは文字列と整数は不変であるため、単純に変更することはできません。おそらく、結果としてそれらを返す必要があります。関数(少なくとも2つの回避策がありますが、Pythonの初心者の場合はお勧めしません)。

編集(適切なコードスタイリング用):

おそらくPEP8を読んで、Pythonスクリプトのコーディング標準を理解する必要があります。これはPythonコミュニティ全体で一般的に使用されており、それに従う必要があります(ある時点でそれを理解する必要があります)。

于 2011-10-26T21:00:42.223 に答える
1

Luhnアルゴリズムに関するウィキペディアの記事から:

def is_luhn_valid(cc):
    num = map(int, str(cc))
    return sum(num[::-2] + [sum(divmod(d * 2, 10)) for d in num[-2::-2]]) % 10 == 0
于 2011-10-26T21:31:43.583 に答える
0

あなたの関数が何をするのか分かりませんが、ここにいくつかの注意があります。

まず、関数を定義する場合は、次の構文を使用します

def is_true(n):
    # do something

この関数をこのように呼び出すことができます。is_true("3884892993")つまり、文字列をとして渡すことができますn。関数は変数nを文字列として扱う必要があります。だからあなたは使うことができます

number = [int(d) for d in n]

これにより、文字列が数字のリストに変換されます。

もう1つの注意:関数return内でステートメントを使用しました。is_trueこのステートメントは、関数の実行を停止し、値を返します。以下のすべてのコードreturnが実行されることはありません。

于 2011-10-26T21:02:27.837 に答える
0

こんな感じかもしれません。コメントを残します

def is_valid(n): #n is the number to be checked.
    numbers = [int(y) for y in n] #converts the string into a list of useable digits.
    double_alt = [sum([int(i) for i in str(x*2)]) for x in numbers[-2::-2]]   #doubles      and sum if more than 10each element of the list altern1.
    sum1 = sum(double_alt) # adds together all the doubled items of the list.
    sum2 = sum(numbers[-1::-2]) #sums the other set of alternating digits.
    sumtotal = sum1 + sum2 #works out the total sum to be worked with.
    return not sumtotal % 10
于 2011-10-26T21:41:56.637 に答える
0

ここに、私が最近作成しなければならなかったluhnアルゴリズムの実装があります。

def is_valid_luhn(cc):
    return not sum([sum(divmod(int(d) * 2, 10)) for d in cc[-2::-2]] + [int(d) for d in cc[-1::-2]]) % 10
    #                          | double |       |--- every -2th --|            |--- every -1th --|
    #                          |--------- step 1 -----------------|
    #              |------------- sum doubled digits --------------|   |-- sum undoubled digits --|
    #          |---------------------- step 2: sum doubled/undoubled digits -----------------------|
    #      |-------------------------- step 3: sum % 10 == 0 --> not sum % 10 --------------------------|

または、より詳細なバージョンが必要な場合:

def is_valid_luhn(cc):
    total = 0
    # Double and sum every 2nd digit starting at -2.
    for d in cc[-2::-2]:
        # divmod(d*2, 10) returns (d*2 // 10, d*2 % 10)
        # sum(divmod) return (d*2 // 10) + (d*2 % 10)
        total += sum(divmod(int(d) * 2, 10))
    # Sum every 2nd digit starting at -1.
    for d in cc[-1::-2]:
        total += int(d)
    # Check module 10 of total: total % 10 == 0 --> not total % 10
    return not total % 10
于 2011-10-27T14:31:52.980 に答える