How to solve this | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

How to solve this

If dad is 71 and son in 35 When the dad age is three times son age I tried to do this but didn't work https://code.sololearn.com/cN6K346MWYn3/?ref=app

30th Sep 2023, 5:45 PM
ZIZO Abd alkawy
6 ответов
+ 5
ZIZO Abd alkawy You just got confused between the son and dad in the if condition, To avoid this type of confusion you should use clear variable names if dad == son * 3: also you should indent the break statement inside the if block, so it breaks after it finds the solution not after the first iteration
30th Sep 2023, 7:00 PM
Mafdi
Mafdi - avatar
+ 6
Just add son's age three times and check if it is equal to dad's age. Code: x=36 b=0 for i in range(0,77): x+=1 b+=1 if b+b+b==x: print(x)
30th Sep 2023, 6:25 PM
Tarun Gautam
Tarun Gautam - avatar
+ 6
I haven't seen that quiz, so I don't know whose age you're supposed to print, but since the difference between their ages never changes, that makes it possible to calculate without iteration, unless the lesson says you're supposed to use a loop. At the ideal point in time, son = (71 - 35) / 2 dad = (71 - 35) / 2 * 3 or graphically, | | | | dad | | son | | | difference
30th Sep 2023, 7:15 PM
Rain
Rain - avatar
+ 4
x=36 b=0 for i in range(0,77): x+=1 b+=1 if x==b*3: #debug1 print(x) break #debug2 #Or: while(1): x+=1 b+=1 if x==b*3: #debug1 print(x) break #debug2 #Or: Since (71-1)/35=2 That: son=(71-35)/2 dad=71-35+son Check: dad/3==son #true
30th Sep 2023, 8:06 PM
Solo
Solo - avatar
+ 2
It can be simplify by working backward. Since dad is 71 and son is 35, they are always 36 years apart. dad, son = 71, 35 for i in range(son-1): # prevent division by zero dad, son = dad-1, son-1 if dad / son == 3: print(f”When dad at {dad} and son at {son}, dad’s age is 3 times of son.”) Output: When dad at 54 and son at 18, dad’s age is 3 times of son. Or you can turn it into a function: def check(dad, son): for i in range(son-1): dad, son = dad-1, son-1 if dad / son == 3: res = f”When dad at {dad} and son at {son}, dad’s age is 3 times of son.” return res print(check(71, 35)) Output: When dad at 54 and son at 18, dad’s age is 3 times of son.
1st Oct 2023, 1:30 AM
Wong Hei Ming
Wong Hei Ming - avatar
0
dad=36 son=0 for i in range(0,77): dad+=1 son+=1 if dad==son*3: print(dad) break def check(dad,son): for i in range(son-1): dad,son=dad-1,son-1 if dad/3==son: print("format")
2nd Oct 2023, 12:32 PM
Freezer Pardon
Freezer Pardon - avatar