0

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.