【问题标题】:Define a function using a variable?使用变量定义函数?
【发布时间】:2011-10-26 20:52:52
【问题描述】:

我正在尝试定义一个包含变量n 的函数,其中n 将是一串数字,例如"3884892993",函数的定义以 is_true(n) 开头,但是如果 n 将是一个字符串,它应该是 is_true(n),然后一旦定义了字符串,我可以使用示例字符串测试函数,例如 @987654328 @。但是,当我使用 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) 从倒数第二个数字开始,一直到第一个数字,将每个交替的数字加倍。 (b) 将加倍的数字相加,将 13 视为 1+3 等,并将结果与​​未加倍的数字相加 数字 (c) 如果总和能被 10 整除,则该数字是有效的信用卡号。

编写并测试一个函数 is_valid(),该函数将信用卡号作为字符串作为参数 (例如有效(“49927398716”))并根据数字是否为 有效的信用卡号码。

【问题讨论】:

  • 好吧,我只是认为使用剪切工具比将其粘贴到此处并确保它提供正确的缩进更容易(无论如何这可能是错误的)。这就是我的新手。它也应该是 PNG,对此感到抱歉。
  • 能否请您打印出您的代码的 JPEG 文件,将其放在 wooden table 上,然后拍照?
  • @Adam Rosenfield 我认为那是讽刺哈哈,我已经放了原始代码。
  • @Adam 谢谢你的笑声。乔治:是的,那是讽刺;)但它非常友好。 “我们”(意思是 SO-ers)需要原始代码,以便我们可以复制/粘贴/运行您的代码。如果您发布我们可以以这种方式运行的内容,您的问题将获得更多(有用的)答案。欢迎来到 S.O.
  • @George:是的,这是个玩笑;我想如果没有链接,它可能会超出人们的想象。

标签: python string integer digits


【解决方案1】:

引号仅用于字符串文字,您不会将变量或参数名称括在引号中以表明它将是一个字符串。函数定义如下所示:

def is_true(n):

然后在函数体中使用n 来引用调用者传入的值。

要对特定值调用函数,您可以:

is_true("3884892993")

建议:为您的函数和变量考虑更多解释性名称。例如,您的函数似乎可以合理地称为is_valid_card_number

【讨论】:

  • 嗨,如果在特定值上调用函数,它会识别使用 n 作为特定值,然后执行函数的其余部分吗?
  • 是的,n 将保存您在 is_true("3884892993") 调用中传递的值。
【解决方案2】:

我不确定你的问题是什么,但如果你想:

  • 正确定义函数:
    • 注意缩进(这是Python要求的!),
    • 有关函数定义的示例,请参阅 here
  • 将字符串变量转换为整数,你可以这样做:

    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 中是不可变的,因此你不能简单地更改它们 -您可能应该将它们作为函数的结果返回(至少有两种解决方法,但如果您是 Python 新手,我不推荐它们)。

编辑(正确的代码样式):

您可能应该阅读PEP 8 以熟悉 Python 脚本的编码标准 - 这是 Python 社区中常用的,您应该遵循它(在某些时候您应该欣赏它)。

【讨论】:

  • 嗨,基本上我只是想让函数读取替换“n”的任何字符串,然后对其执行操作。
  • @GeorgeBurrows:好的,我刚刚更新了我的答案,所以它可能会更好地回答你的问题。
  • 嗨,所以基本上我不能用字符串测试代码?如果是这样,那会很烦人,因为我现在几乎不可能发现问题,哈哈,谢谢您的帮助。
  • @GeorgeBurrows:当然可以。我要说的是,您不应该期望在调用函数后更改传递给函数的变量。您也不应该认为'3' / 13 / 1 相同(并且您通常不能对字符串执行您可以对整数执行的操作)。够清楚吗?
【解决方案3】:

来自Wikipedia article on the Luhn algorithm

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

【讨论】:

  • 遗憾的是,我不允许公然抄袭,必须写一些原创的东西,这对于只有 3 周经验的人来说要求很高:(
【解决方案4】:

我不知道你的函数应该做什么,但这里有一些说明。

首先,如果你定义了函数,那么你使用下面的语法

def is_true(n):
    # do something

你可以像is_true("3884892993")这样调用这个函数,即你可以将字符串作为n传递。您的函数现在需要将变量 n 视为字符串。所以你可以使用

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

这将导致将字符串转换为数字列表。

还有一点:您在 is_true 函数中使用了 return 语句。该语句将停止执行函数并返回值。 return 下面的每一个代码都不会被执行。

【讨论】:

  • 该函数旨在接受一个由 11 个数字组成的输入字符串,然后用这些数字取倒数第二个数字开始的交替数字并向后工作,将这些数字加倍,然后将数字相加,例如如果你有 18 和 3,你会做 1 + 8 + 3。然后将该总和添加到未加倍的剩余数字的总和中,然后计算它是否是 10 的倍数,如果它打印为真,如果不是然后打印错误。我不确定这样做对专家来说有多复杂,但对我来说,3 周前才开始学习 python,这是不可能的。
  • 抱歉,第二行应该是“交替数字”
  • 我也不知道为什么我在里面加上了一个'return',谢谢你的位置。
【解决方案5】:

可能是这样的。我离开你的cmets

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

【讨论】:

    【解决方案6】:

    这里是我最近要做的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      相关资源
      最近更新 更多