Основной код угадывателя

parent 5aceb094
"""This program searches for a number in a given diapason, by eliminating half of the variants
and then trying all others at random, storing made guesses in an array"""
import random
# array of tried numbers
tries = []
# number of tries it took to guess the number
number_of_tries = 0
# the correct guess
the_correct_guess = 0
# main function of the program
def guess(min, max, number):
"""
Main function exspects three arguments:
range in two int variables
and the number to guess also in int
"""
#importing the tries array, the number of tries and the correct guess
global tries
global number_of_tries
global the_correct_guess
# eliminating half of the variants
# by checking if the number is
# bigger or smaller than the middle of min and max
if number < max - ((max - min) / 2):
# creating a current guess by getting a random variable in the new range
current_guess = random.randint(min, (max - int((max - min) / 2)))
# if the guess is correct print the number of tries,
# the guessed number and all the tried numbers
if current_guess == number:
print(
f"The number was {current_guess} and it took {number_of_tries} tries to guess it."
)
print(f"The tries were {tries}")
the_correct_guess = current_guess
# if not check if the guess was already made and
# if not add it to the tries array and check again
else:
if current_guess in tries:
guess(min, max, number)
else:
tries.append(current_guess)
number_of_tries += 1
guess(min, max, number)
# same as previous steps but if the range is in the latter half
else:
current_guess = random.randint(max - int((max - min) / 2), max)
if current_guess == number:
print(
f"The number was {current_guess} and it took {number_of_tries} tries to guess it."
)
print(f"The tries were {tries}")
the_correct_guess = current_guess
else:
if current_guess in tries:
guess(min, max, number)
else:
tries.append(current_guess)
number_of_tries += 1
guess(min, max, number)
# test
def test_guess():
global the_correct_guess
guess(1, 10, 5)
return the_correct_guess == 5
print(test_guess())
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment