title: Terminated due to timeout error in sum of digit factorials
body: <p><a href="https://projecteuler.net/problem=254" rel="nofollow noreferrer">link</a> for the question</p>
  <p>Define f(n) as the sum of the factorials of the digits of n. For example, f(342) = 3! + 4! + 2! = 32.</p>
  <p>Define sf(n) as the sum of the digits of f(n). So sf(342) = 3 + 2 = 5.</p>
  <p>Define g(i) to be the smallest positive integer n such that sf(n) = i. Though sf(342) is 5, sf(25) is also 5, and it can be verified that g(5) is 25.</p>
  <p>Define sg(i) as the sum of the digits of g(i). So sg(5) = 2 + 5 = 7.</p>
  <p>Further, it can be verified that g(20) is 267 and ∑ sg(i) for 1 ≤ i ≤ 20 is 156.</p>
  <p>What is ∑ sg(i) for 1 ≤ i ≤ 150?</p>
  <p>I am getting an error <code>Terminated due to timeout</code> on hacker rank. This is my code
  <a href="https://i.stack.imgur.com/2Tvij.png" rel="nofollow noreferrer">this is the error i am getting</a></p>
  <pre><code>def f(n):
      from math import factorial
      lst_n = list(map(int, str(n).strip()))
      s=0
      for i in lst_n:
          s += factorial(i)
      return s
  def sf(n):
      return sum(list(map(int, str(f(n)))))
  
  def g(i):
      for n in range(1, 100000000):
          if sf(n)==i:
              break
      return n
  def sg(n):
      s= 0
      for i in range(1, n+1):
          s += sum(list(map(int, str(g(i)))))
      return s
  N= int(input())
  LST=[]
  for i in range(N):
      LST.append(list(map(int, input().strip().split())))
  for i in range(N):
      print(sg(LST[i][0]))
  </code></pre>