Home > other >  improve recursion efficiency in python
improve recursion efficiency in python

Time:10-18

def f(n):
    if n == 1:
        return 1
    else:
        return (1 / (n - 1)) * (f(n - 1)   (1 / f(n - 1)))


n = int(input())
print(str(round(f(n),2)))

It's been said that my code is not efficient enough since there are two f(n-1)s in the recursion. How can I improve it ?

CodePudding user response:

def f(n):
    if n == 1:
        return 1
   
else:
    return (1 / (n - 1)) * (f(n - 1)   (1 / f(n - 1)))

n = int(input())
print(str(round(f(n),2)))

#as long as n gets bigger the function will turn into infinite loop

You can try this:

else:
   def alternative(n):
       s= (1 / (n - 1))
        def altr(s):
            return  (n - 1)   (1 / (n - 1)) 
        

CodePudding user response:

If you use python ≥ 3.8 you could use an assignment expression:

def f(n):
    if n == 1:
        return 1
    else:
        return (1/(n-1)) * ((F:=f(n-1))   (1/F)) # (F:=…) gets evaluated as …
                                                 # and instantiates F
    
n = int(input())
print(str(round(f(n),2)))
  • Related