Can anyone explain how this program works ? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

Can anyone explain how this program works ?

def f(n): if n==0: return 0 else: return f(n-1)+10 print(f(5))

15th Jul 2020, 4:55 AM
Shreepriya HA
3 Réponses
15th Jul 2020, 5:08 AM
BroFar
BroFar - avatar
+ 3
This is an inductive definition of a function f, f(n) = f(n-1)+10 with base case, f(0)=0; In order to understand what this code does, let's see how this gets executed >>f(5) = f(4)+10 >>f(5) = (f(3)+10)+10 {because f(4)= f(3)+10} Similarly, f(5) = (f(2) +10) +10 + 10 f(5) = (f(1) +10) +10 + 10 + 10 f(5) = (f(0) +10) +10 + 10 + 10 +10 So, f(5) = 50 This code will output 50
15th Jul 2020, 5:07 AM
hackxsaras
+ 3
Thank you
15th Jul 2020, 5:27 AM
Shreepriya HA