Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Analysis
- Test set 1
- Since A = 0 and B = 30 in this test set, and since we get N = 30 tries per test case, we can simply guess every number
- from 1 to 30 until the judge sends back CORRECT.
- Test set 2
- In test set 2, since the answer could be anywhere in the range (0, 109] and we still have only 30 guesses, we will use binary search.
- Initially, we know the answer P is in [1, 109], which is a big range! To cut that range by half, our first guess will be (1 + 109) / 2 = 5×108.
- If the judge sends back TOO_SMALL, we will know that P is in [1, 5×108).
- Similarly, if the judge sends back TOO_BIG, P is in (5×108, 109]. Otherwise, P is 5×108 and we are done.
- '''
- from random import randrange
- from math import log2
- def help(guess, r):
- if guess > r:
- print("Your guess (" + str(guess) + ") is greater than the desired number.")
- return 1
- elif guess < r:
- print("Your guess (" + str(guess) + ") is lower than the desired number.")
- return -1
- else:
- print("CORRECT - Your guess (" + str(guess) + ") is equal to the desired number.")
- return 0
- # ******** 1. Initialization of the problem ********
- print()
- akro1 = 1
- akro2 = 10**6
- N = 20
- counter = 0
- r = randrange(akro1, akro2 + 1)
- guesses = list()
- RIGHTN = log2(akro2 - akro1 + 1)
- if RIGHTN != int(RIGHTN):
- RIGHTN = int(RIGHTN) + 1
- print("**********************************************************")
- print(" akro1 =", akro1, "akro2 =", akro2, "r =", r)
- print("N = " + str(N) + ", minimumN I need for sure is " + str(int(RIGHTN)))
- print("**********************************************************")
- print()
- # ******** 2. First guess to start the problem ********
- guess = (akro1 + akro2) // 2
- guesses.append(guess)
- answer = help(guess, r)
- counter += 1
- # ******** 3. In all the cases, I will apply the binary search ********
- foundAnswer = False
- while answer != 0 and counter < N:
- if answer == 1:
- # That means that my guess is GREATER, so I have to check in the down "sub-interval"
- akro2 = guess
- guess = (akro1 + akro2) // 2
- counter += 1
- else:
- akro1 = guess
- guess = (akro1 + akro2) // 2
- counter += 1
- answer = help(guess, r)
- if answer == 0:
- foundAnswer = True
- break
- print()
- print("**********************************************************")
- if foundAnswer == True:
- print("Correct answer = " + str(guess))
- print("Number of guesses = " + str(counter))
- print("Limit = N = " + str(N))
- else:
- print("Correct answer was " + str(r), ", but your last guess was " + str(guess))
- print("You ran out of tries....")
- print("Number of guesses = " + str(counter))
- print("Limit = N = " + str(N))
- print("**********************************************************")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement