280 views
1 vote
Set up a python program

Use the randint function to generate 100 3-digit
random numbers and put them in a list.
Then write a guessing routine which keeps guessing
numbers until it guesses one of the numbers in the list.
Count how many guesses it takes.
A
Do not use prepacked functions such as index or find
and do not use the "in" operator. Write a sequential
search that uses a loop and comparison to search for
numbers.

User Uraza
by
6.7k points

1 Answer

5 votes

Answer:

# Import the randint function from the random module

from random import randint

# Create an empty list to store the numbers

numbers = []

# Generate 100 random 3-digit numbers

for i in range(100):

numbers.append(randint(100, 999))

# Set the initial number of guesses to 0

num_guesses = 0

# Keep guessing numbers until a number in the list is found

while True:

# Increment the number of guesses

num_guesses += 1

# Guess a number

guess = randint(100, 999)

# Search for the guess in the list using a loop and comparison

found = False

for num in numbers:

if num == guess:

# The guess was found in the list

found = True

break

# If the guess was found in the list, print the number of guesses and end the loop

if found:

print("Found a number in the list after %d guesses." % num_guesses)

break

User Pierre Espenan
by
6.7k points