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
6 RĂ©ponses
+ 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
+ 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)
+ 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
+ 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
+ 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.
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")