简体   繁体   English

需要帮助理解Python片段。

[英]Need help understanding a Python snippet.

I came across this python snippet recently and can someone tell me what does the for loop in the return statement do? 我最近遇到了这个python片段,有人可以告诉我return语句中的for循环是做什么的吗?

def dec(num, num_dig):
    if num_dig==0:
        return int(num==1)
    else:
        return sum(dec(num/i, num_dig-1) for i in range(1,10) if num/i*i==num)

Apparently, the question was about finding the no. 显然,问题是关于找不到。 of x-digit numbers whose product equals N. Thanks, in advance 产品等于N的x位数字。谢谢,提前

The for loop is called a generator expression, and is similar to a list comprehension. for循环称为生成器表达式,类似于列表推导。 You can think of it as generating a list of numbers by taking all the numbers between 1 and 9 inclusive, only taking those for which the condition num/i*i==num is true, and then transforming those numbers using the expression dec(num/i, num_dig-1) . 您可以将其视为生成一个数字列表,方法是取所有数字在1和9之间,包括条件num/i*i==num为真,然后使用表达式dec(num/i, num_dig-1)转换这些数字dec(num/i, num_dig-1)

Then the sum of all of these final numbers is taken. 然后取所有这些最终数字的总和。

Another way to write this, which is more verbose and less Pythonic but might be more clear if you come from systems languages is: 写这个的另一种方法,更简洁,更少Pythonic,但如果你来自系统语言可能会更清楚:

total = 0
for i in range(1,10):
   if num/i*i == num:
     total += dec(num/i, num_dig-1)
return total

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM