3.4 Exercises
75
if a < b:
print(’\na is the smallest of the two numbers’)
elif a == b:
print(’\na and b are equal’)
else:
print(’\na is the largest of the two numbers’)
Proceed by writing the program, and then run it a few times with different values
for a and b to confirm that it works as intended. In particular, choose combinations
for a and b so that all three branches of the if construction get tested.
Filename: compare_a_and_b.py.
Remarks The program is not too robust, since it assumes the user types an integer
as input (a real number gives trouble).
Exercise 3.6: Area of Rectangle Versus Circle
Consider one circle and one rectangle. The circle has a radius r = 10.6. The
rectangle has sides a and b, but only a is known from the outset. Let a = 1.3
and write a program that uses a while loop to find the largest possible integer b that
gives a rectangle area smaller than, but as close as possible to, the area of the circle.
Run the program and confirm that it gives the right answer (which is b = 271).
Filename: area_rectangle_vs_circle.py.
Exercise 3.7: Frequency of Random Numbers
Write a program that takes a positive integer N as input and then draws N random
integers from the interval [1, 6]. In the program, count how many of the numbers,
M, that equal 6 and print out the fraction M/N. Also, print all the random numbers
to the screen so that you can check for yourself that the counting is correct. Run the
program with a small value for N (e.g., N = 10) to confirm that it works as intended.
Hint Use random.randint(1,6) to draw a random integer between 1 and 6.
Filename: count_random_numbers.py.
Remarks For large N, this program computes the probability M/N of getting six
eyes when throwing a dice.
Exercise 3.8: Game 21
Consider some game where each participant draws a series of random integers
evenly distributed between 0 and 10, with the aim of getting the sum as close as
possible to 21, but not larger than 21. You are out of the game if the sum passes 21.
After each draw, you are told the number and your total sum, and are asked
whether you want another draw or not. The one coming closest to 21 is the winner.
Implement this game in a program.
Hint Use random.randint(0,10) to draw random integers in [0, 10].
Filename: game_21.py.
Précédent

- 97/350

Suivant