Last active
November 13, 2022 08:42
-
-
Save naemazam/c7d6349fffd2686ae898abe6f34f4286 to your computer and use it in GitHub Desktop.
write a recursive function. When the age (x) of the second person and total number (N) are input, the list of age composition of all people is output in reverse order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' Suppose there are N people now, the first person is 3 years old, the second person is x years old | |
(unknown), and the age of the third person is the sum of the ages of the first two people, and so | |
on until the Nth person. Try to write a recursive function. When the age (x) of the second person | |
and total number (N) are input, the list of age composition of all people is output in reverse order. | |
Note: when the age of the M-th person is greater than 120, output ”Larger than 120!“ and the | |
reverse order list of the age of the first M-1 individuals. | |
[example input 1] | |
6,4 | |
[sample output 1] | |
[15, 9, 6, 3] | |
[example input 2] | |
80,9 | |
[sample output 2] | |
Age 4 is larger than 120! | |
[83, 80, 3 ''' | |
def getAge(n,x): | |
if n==1: | |
return 3 | |
if n==2: | |
return x | |
return getAge(n-1,x)+getAge(n-2,x) | |
flag=0 | |
f1=3 | |
x,n=map(int,input().split(',')) | |
l=[x,f1] | |
for i in range(3,n+1): | |
a=getAge(i,x) | |
if a>120: | |
flag=i | |
break | |
else: | |
l.insert(0,a) | |
if flag!=0: | |
print('Age',flag,'is larger than 120!') | |
print(l) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment