简体   繁体   中英

python Traceback (most recent call last):

I'm trying to create a guessing game, but I'm running into some errors, can anyone help me?

A = A + [i]
# Define two variables which will be the end point of
# the search span 
mini = 0 
maxi = len(A) - 1 
stepcounter = 1 
find = int(input("Think of a number between 1 and 1000")) 
def guessgame(find, A, mini, maxi, stepcounter): 
    # This calculates the value of the midpoint element 
    # in the list guess = (A[mini] + A[maxi]) // 2 
    if guess == find: 
        return 
        print("You think of", guess, "I did this in", stepcounter, "number of steps") 
    elif guess < find: 
        mini = guess 
        stepcounter = stepcounter + 1 
        guessgame(find, A, mini, maxi, stepcounter) 
    elif guess > find: 
        maxi = guess 
        stepcounter = stepcounter + 1 
        guessgame(find, A, mini, maxi, stepcounter) 
    else: 
        return 
        print("Not in array") 
        guessgame(find, A, mini, maxi, stepc

ounter)

my error is

traceback most recent call last:
line 34 guessgame(find, a, mini,maxi, supercounter)

File "C:/Users/Acer VN7/PycharmProjects/untitled1/py.py", line 20, in guessgame
if guess == find:
RecursionError: maximum recursion depth exceeded in comparison

The main problem you have is that you confuse the guess with its position. You compute guess to be the midpoint of the values in A , but then you set mini or maxi to the guess , rather than its position. I expect that this confusion drives your guess out of the binary search range, and you get an infinite recursion.

To debug this problem, add a few print statements to track execution. For instance, the first line of your function should be something like

print find, mini, maxi

Then, when you compute guess and move one endpoint, print out those values before you leave the routine.

You seem to have omitted the code that puts values into A , so I'm not at all sure what's in there.

Beyond that, there are structural problems. You can't get to the code after return in your if and else branches. You can't get to the else branch at all, since the first three branches cover all possibilities (law of excluded middle).

Does this get you moving?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM