简体   繁体   中英

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?

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

The for loop is called a generator expression, and is similar to a list comprehension. 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) .

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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