【发布时间】:2020-04-23 08:59:03
【问题描述】:
我是生成器的新手,我认为我可以练习为 luhn 数字函数编写生成器。 Luhn 号码是有效的信用卡/借记卡号码(没有骗局,我在书中看到一个简单的练习并决定改进它)
我写了以下代码:
from random import randint
def random_n(n):
range_start = 10 ** (n-1)
range_end = (10**n) - 1
return randint(range_start, range_end)
def get_luhn_number():
while True:
eight_digit = random_n(16).__str__()
# *2 of even positioned numbers
eight_digit = [int(i)*2 if eight_digit.index(i) % 2 == 0 else int(i) for i in eight_digit]
# turning 2 digit numbers to one digit
eight_digit = [1+(i-10) if i >= 10 else i for i in eight_digit]
if sum(eight_digit) % 10 == 0:
yield eight_digit
f = get_luhn_number()
x = False
while not x:
x = next(f)
print(x)
打印的值始终是卢恩数。
但我刚刚意识到,可以使用简单的返回函数来代替生成器:
from random import randint
def random_n(n):
range_start = 10 ** (n-1)
range_end = (10**n) - 1
return randint(range_start, range_end)
def get_luhn_number():
while True:
eight_digit = random_n(16).__str__()
# *2 of even positioned numbers
eight_digit = [int(i)*2 if eight_digit.index(i) % 2 == 0 else int(i) for i in eight_digit]
# turning 2 digit numbers to one digit
eight_digit = [1+(i-10) if i >= 10 else i for i in eight_digit]
if sum(eight_digit) % 10 == 0:
return eight_digit
print(get_luhn_number())
而且打印出来的值总是一个 luhn 数。
为什么我应该使用生成器代码而不是函数代码?
感谢您的帮助
编辑:
我得到的输出是 16 个数字的列表,我只是没有加入它们。
【问题讨论】:
-
生成器会生成一个 stream 数字,您可以对其进行迭代:
for n in get_luhn_number(): ...。对于return,while循环是多余的,因为您总是会在第一次迭代时退出循环,并且函数的返回值根本不可迭代。 -
Dunder 方法并不意味着显式调用;请改用
str(random_n(16))。 -
是否可以从生成器中获取 N 个 luhn 数?即从生成器打印 5 个 luhn 数字,或任何 n 个 luhn 数字?
-
first_five = list(itertools.islice(get_luhn_number(), 5)) -
谢谢大家。我只是想看看将它作为回报和作为发电机有什么区别。这是我的第一台发电机,但仍然不知道它的全部潜力。
标签: python python-3.x algorithm generator