Problem Description
If a ball falls freely from a height of 100 meters, it bounces back to half of its original height each time it hits the ground, and then falls again. How many meters does it pass when it hits the ground for the 10th time? How high is the 10th rebound?
solution
First, analyze the problem and calculate its value according to the problem with a mathematical geometric sequence. From the problem, it can be known that the problem function can be solved with a recursive function. First, use the function definition symbol def to customize a new function, and use the row recursive function to repeat the input value Loop, and then use the for loop to assign a value to the number of drops of the ball in the question, get the tenth drop value, and then use return to return the obtained value and output the previously defined function value. Still need to calculate sums, when judging the return value, pay attention to whether the function value to be printed meets the definition of recursive function.
Code example:
def row(n, sums, height):#def is a symbol to define a new function,row means that this function is a recursive function.if n ==10:return sums
print(sums, height)returnrow(n+1, sums+(height*2), height/2) # row()Represents returning the value in the recursive function to the output.print(row(1,100,50))
1005020025.0250.012.5275.06.25287.53.125293.751.5625296.8750.78125298.43750.390625299.218750.1953125299.609375
Conclusion
Learn to master the calculation methods in python functions, use recursive functions to solve problems, and be familiar with the use of if conditions in python. Learn the meaning of functions returned in python functions.
END
Chief Editor | Wang Nanlan
Responsible Editor | Shen Zhijian
**The stronger the ability, the greater the responsibility. Seek truth from facts, rigorous and meticulous. **
** ——Where2go team**
Recommended Posts