Python Practice Example 20
Problem:A ball falls freely from a height of 100 meters. After each landing, it bounces back to half of its original height; then it falls again. Find out how many meters it has traveled in total by the 10th landing, and how high it bounces on the 10th rebound.
Program analysis:None
Program source code:
Python Example 1
#!/usr/bin/python
# -*- coding: UTF-8 -*-
tour = []
height = []
initial_height = 100.0 # Initial height
num_bounces = 10 # Number of bounces
for i in range(1, num_bounces + 1):
# Starting from the second landing, the distance traveled should be the bounce height multiplied by 2 (bounce to the highest point and fall again)
if i == 1:
tour.append(initial_height)
else:
tour.append(2 * initial_height)
initial_height /= 2
height.append(initial_height)
total_distance = sum(tour)
final_bounce_height = height[-1]
print(f"Total height: tour = {total_distance}")
print(f"The {num_bounces}th bounce height: height = {final_bounce_height}")
The output of the above example is:
总高度:tour = 299.609375 第10次反弹高度:height = 0.09765625
Example 2
def calculate_distance_and_height(height, times):
total_distance = 0
current_height = height
for i in range(1, times + 1):
# Starting from the second landing, the distance traveled should be the bounce height multiplied by 2 (bounce to the highest point and fall again)
if i == 1:
total_distance += current_height
else:
total_distance += current_height * 2 # The distance of each fall and bounce
current_height /= 2 # Height after bounce
return total_distance, current_height
# Initial height is 100 meters; calculate the total distance and bounce height at the 10th landing
height = 100
bounce_times = 10
total_distance, final_height = calculate_distance_and_height(height, bounce_times)
print(f"By the {bounce_times}th landing, it has traveled a total of {total_distance} meters.")
print(f"The height of the {bounce_times}th rebound is {final_height} meters.")
total_distance = 0
current_height = height
for i in range(1, times + 1):
# Starting from the second landing, the distance traveled should be the bounce height multiplied by 2 (bounce to the highest point and fall again)
if i == 1:
total_distance += current_height
else:
total_distance += current_height * 2 # The distance of each fall and bounce
current_height /= 2 # Height after bounce
return total_distance, current_height
# Initial height is 100 meters; calculate the total distance and bounce height at the 10th landing
height = 100
bounce_times = 10
total_distance, final_height = calculate_distance_and_height(height, bounce_times)
print(f"By the {bounce_times}th landing, it has traveled a total of {total_distance} meters.")
print(f"The height of the {bounce_times}th rebound is {final_height} meters.")
The output of the above example is:
第10次落地时,共经过 299.609375 米。 第10次反弹的高度为 0.09765625 米。Other extensions
Python 100 Examples