Reputation: 33
My program is supposed to guess a number. First, the user guesses a number (in their head) and doesn't tell the computer. Then, the computer starts to guess the number. The user sees the number the computer guessed and sends one of three types of string:
I have a problem: when the system guesses the number it takes too long to find the answer because range of random doesn't change in the program. Can somebody help me improve the code to become more efficient?
import random
b = 0
a = 0
hads = random.randint(1,99)
print(hads)
user = str(input('bigger or lower number : '))
while user != 'c':
if user == 'b':
a = hads
b = 99
elif user == 'l':
b = hads
a = 1
hadss = random.randint(a,b)
print(hadss)
user = str(input('bigger or lower number : '))
print('woooow')
Upvotes: 3
Views: 115
Reputation: 104
I would write it this way.
import sys
import random
b = 99
a = 1
user=''
hads = random.randint(a,b)
while user != 'c':
print hads
print a, ' ',b
user = input('bigger or lower number : ')
print user
if user == 'b':
a = hads
elif user == 'l':
b = hads
hads = random.randint(a, b)
print('woooow')
Upvotes: 0
Reputation: 83537
If the number is too big, then you should change b
, but leave a
the same. Similarly, if the number is too low, then you should change a
and leave b
the same:
if user == 'b':
a = hads
elif user == 'l':
b = hads
This is very similar to a "binary search". I suggest you read about this fundamental algorithm.
You should also read this article to learn some tricks to debug your code.
Upvotes: 1
Reputation: 1749
I think you should initiate the a and b at the very beginning, then in the loop you can just change the one variable. The problem you have is you constantly reset the a
and b
to their initial value 1
and 99
, so basically your code just randomly guesses between 1
and 99
, and this is why it takes so long!
import random
b = 99
a = 1
hads = random.randint(a,b)
print(hads)
user = str(input('behem begoo cheghadr fasele daram : '))
while user != 'c':
if user == 'b':
a = hads
elif user == 'l':
b = hads
hads = random.randint(a,b)
print(hads)
user = str(input('behem begoo cheghadr fasele daram : '))
print('woooow')
Upvotes: 1
Reputation: 104
You started with hads and then wrote hadss. You never use hadss after the assignment. Change that to hads and it should work.
Upvotes: 0