Ball drop Python question

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

The body of the question.

If you place the ball from a high place and make it fall naturally, it will bounce two-thirds of its original height every time it touches the floor. However, when it reaches a height of less than 1 cm from the floor, it no longer bounces.

Implement a bouncy() function that returns the sum of all the heights of the bounced ball until it no longer bounces when the ball falls free from n cm height. However, the return value is rounded to the third decimal place.

defbouncy(n):
  sum = 0.0
  bounceHeight = n * (2.0 / 3.0)

  while bounceHeight > 1.0:
    sum += bounceHeight
    bounceHeight *= round(2.0 / 3.0)
    break
  return sum
assert bouncy(1) == 0
assert bouncy(2) == 2.22
assert bouncy(10) == 18.24

This is the code written by , and only the assistant (1) below does not have an error, and 2 and 10 will have an error. What should I do to prevent errors? ㅜ<

  ---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-149-7c759e297230> in <module>()
      9   return sum
     10 assert bouncy(1) == 0
---> 11 assert bouncy(2) == 2.22
     12 assert bouncy(10) == 18.24

<ipython-input-149-7c759e297230> in bouncy(n)
      5   while bounceHeight > 1.0:
      6     sum += bounceHeight
----> 7     bounceHeight *= round(2.0 / 3.0)
      8 
      9   return sum

KeyboardInterrupt: 

python

2022-09-20 10:55

1 Answers

Hello.

I wrote the code myself. I've written an explanation in the notes, so if you follow the flow carefully, you'll understand.

def bouncy(n):
    sum = 0 # Store the sum of the bounced distances

    while True:
        if n <= 1:
            Break # If the height is less than or equal to 1, the repeat statement is terminated

        n * = 2/3 # Bouncing distance is set to 2/3 of the original distance
        sum + = n # Add the bouncing distance to the total

    Return round (sum, 2) # Round to third decimal place

The algorithm just needs to move the solution to code as if it were writing.


2022-09-20 10:55

If you have any answers or tips


© 2022 pinfo. All rights reserved.