Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (16.4k points)

A number is said to be a strong number if the sum of the factorials of the individual digits is equivalent to the number itself. For instance: 145 = 1! + 4! +5! 

I composed the accompanying code in python for this:

import math

def strong_num():

    return [x for x in range(1,1000) if x==int(reduce(lambda p,q:math.factorial(int(p))+math.factorial(int(q)),str(x)))]

print strong_num()

I don't know where this code went wrong??

1 Answer

0 votes
by (26.4k points)

Your reduce input isn't right, at that point you shouldn't figure the factorial of p. Truth be told, it is simpler to simply utilize the sum 

return [x for x in range(1, 1000) 

          if x == sum(math.factorial(int(q)) for q in str(x))]

functions.reduce function will be considered as:

reduce(f, [a, b, c, d, ...]) == f(f(f(a, b), c), d) ...

In this way, for example, if that x == 145, at that point your reduce part will compute

   int(reduce(lambda p, q: factorial(int(p)) + factorial(int(q)), str(x)))

== int(reduce(lambda p, q: factorial(int(p)) + factorial(int(q)), "145"))

== int(factorial(factorial(1) + factorial(4)) + factorial(5))

== int(factorial(1 + 24) + 120)

== int(15511210043330985984000000 + 120)

== 15511210043330985984000120

The interpreter doesn't complete likely because of expecting to process the factorial of a very huge number (consider (2 × 9!)!...) 

In the event that you actually need to keep the reduce, you should transform it to:

 reduce(lambda p,q: p + math.factorial(int(q)),  str(x),  0)

#                   ^                                     ^

#                   No need to factorial                  Add initializer too

Join the Python online course today for learning Python programming and get certified.

Browse Categories