Python Exercise Example 20
**Problem:** A ball is dropped freely from a height of 100 meters. Each time it hits the ground, it bounces back to half of its previous height and falls again. Find the total distance traveled when it hits the ground for the 10th time, 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 time, the distance when hitting the ground should be the rebound height multiplied by 2 (bounce to the highest point and then fall)
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
]
(
f
"
Total height: tour = {total_distance}
"
)
(
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 time, the distance when hitting the ground should be the rebound height multiplied by 2 (bounce to the highest point and then fall)
if
i
==
1
:
total_distance +
=
current_height
else
:
total_distance +
=
current_height *
2
The distance of each fall and rebound
current_height /
=
2
The height after rebound
return
total_distance
,
current_height
With an initial height of 100 meters, calculate the total distance and rebound height at the 10th landing
height
=
100
bounce_times
=
10
total_distance
,
final_height
=
calculate_distance_and_height
(
height
,
bounce_times
)
(
f
"At the {bounce_times}-th landing, the total distance traveled is {total_distance} meters."
)
(
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 米。
Python 100 Examples