Problem 34 : Digit factorials

Problem Statement

145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.

Find the sum of all numbers which are equal to the sum of the factorial of their digits.

Note: as 1! = 1 and 2! = 2 are not sums they are not included.

Solution

def factorial(x):
    fact = 1  
    for i in range(1,x+1): 
        fact = fact * i 
    return fact

val=[]
for i in range(3,10**6):
    a=str(i)
    sum1=0
    
    for j in a:
        sum1=sum1+factorial(int(j))
    if int(a) == sum1 : 
        val.append(int(a))
    
print(sum(val))

Output

40730