Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6915599
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T09:29:44+00:00 2026-05-27T09:29:44+00:00

Maybe the problem can be solved by deleting all those functions, can’t it? However,

  • 0

Maybe the problem can be solved by deleting all those functions, can’t it?
However, i really don’t know what to do to get the source work.
By the way, it just simulates a horse in a chesstable, going around and around, randomly, trying to visit each square once; and I get a recursion depth exceeded error.

import random

def main():
    global tries,moves
    tries,moves=0,0
    restart()

def restart():
    global a,indexes,x,y
    a=[[0 for y in range(8)] for x in range(8)] #Costrutto chic
    indexes=[x for x in range(8)]
    #Random part
    x=random.randint(0,7)
    y=random.randint(0,7)
    a[x][y]=1
    start()

def start():
    global i,indexes,moves,tries
    i=0
    random.shuffle(indexes) #List filled with random numbers that i'll use as indexes
    while i<=7:
        if indexes[i]==0:
            move(-2,-1)
        elif indexes[i]==1:
            move(-2,1)
        elif indexes[i]==2:
            move(-1,-2)
        elif indexes[i]==3:
            move(-1,2)
        elif indexes[i]==4:
            move(1,-2)
        elif indexes[i]==5:
            move(1,2)
        elif indexes[i]==6:
            move(2,-1)
        elif indexes[i]==7:
            move(2,1)
        i+=1
    for _ in a:
        if 0 in _:
            print "Wasted moves: %d"%(moves)
            tries+=1
            moves=0
            restart()
    print "Success obtained in %d tries"%(tries)

def move(column,row):
    global x,y,a,moves
    try: b=a[x+row][y+column]
    except IndexError: return 0
    if b==0 and 0<=x+row<=7 and 0<=y+column<=7:
        x=x+row
        y=y+column
        a[x][y]=1
        moves+=1
        start()
    else: return 0

try :main()
#except: print "I couldn't handle it" <-Row added to prevent python from returning a huge amount of errors

EDIT: This is the modified version, which still does not works, but at least it’s an improvement:

import random

def move((column,row),x,y):
    try: cell=squares_visited[x+row][y+column]
    except IndexError: return x,y ## NONE TYPE OBJECT
    if cell==0 and 0<=x+row<=7 and 0<=y+column<=7:
        x+=row
        y+=column
        squares_visited[x][y]=1
        return x,y ## NONE TYPE OBJECT

squares_visited=[[0] * 8 for _ in range(8)]
x=random.randint(0,7)
y=random.randint(0,7)
squares_visited[x][y]=1
moves=[(-2,-1),(-2,1),(-1,-2),(-1,2),(1,-2),(1,2),(2,-1),(2,1)]
indexes=list(range(8))
tries=0
print "The horse starts in position %d,%d"%(x,y)

while True:
    random.shuffle(indexes)
    for _ in indexes:
        cells=move(moves[indexes[_]],x,y) ##Passing as arguments x and y looks weird
        x=cells[0]
        y=cells[1]
    #If you out this for cicle, there are no legal moves anymore(due to full completion with 1, or to lack of legit moves)
    for _ in squares_visited:
        if 0 in _:
            squares_visited=[[0] * 8 for _ in range(8)]
            tries+=1
    else:
        print "You managed to do it in %d tries."%(tries)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T09:29:45+00:00Added an answer on May 27, 2026 at 9:29 am

    This code has a lot of problems — enough that it’s worth going over in full:

    import random
    
    def main():
        global tries,moves
    

    The first of many examples of over-use of global variables. When possible, pass parameters; or create a class. This is a general strategy that will help you construct more comprehensible (and thus more debuggable) algorithms; and in a general sense, this is part of why your code fails — not because of any particular bug, but because the complexity of your code makes it hard to find bugs.

        tries,moves=0,0
        restart()
    
    def restart():
        global a,indexes,x,y
    

    Why do you name your board a? That’s a terrible name! Use something descriptive like squares_visited.

        a=[[0 for y in range(8)] for x in range(8)] #Costrutto chic
        indexes=[x for x in range(8)]
    

    Minor: in python 2, [x for x in range(8)] == range(8) — they do exactly the same thing, so the list comprehension is unnecessary. In 3, it works a little differently, but if you want a list (rather than a range object) just pass it to list as in (list(range(8))).

        #Random part
        x=random.randint(0,7)
        y=random.randint(0,7)
        a[x][y]=1
        start()
    

    So my understanding of the code so far is that a is the board, x and y are the starting coordinates, and you’ve marked the first spot visited with a 1. So far so good. But then things start to get hairy, because you call start at the end of restart instead of calling it from a top-level control function. That’s theoretically OK, but it makes the recursion more complicated than necessary; this is another part of your problem.

    def start():
        global i,indexes,moves,tries
    

    Argh more globals…

        i=0
        random.shuffle(indexes) #List filled with random numbers that i'll use as indexes
        while i<=7:
            if indexes[i]==0:
                move(-2,-1)
            elif indexes[i]==1:
                move(-2,1)
            elif indexes[i]==2:
                move(-1,-2)
            elif indexes[i]==3:
                move(-1,2)
            elif indexes[i]==4:
                move(1,-2)
            elif indexes[i]==5:
                move(1,2)
            elif indexes[i]==6:
                move(2,-1)
            elif indexes[i]==7:
                move(2,1)
            i+=1
    

    Ok, so what you’re trying to do is go through each index in indexes in sequence. Why are you using while though? And why is i global?? I don’t see it being used anywhere else. This is way overcomplicated. Just use a for loop to iterate over indexes directly, as in

        for index in indexes: 
            if index==0:
                ...
    

    Ok, now for the specific problems…

        for _ in a:
            if 0 in _:
                print "Wasted moves: %d"%(moves)
                tries+=1
                moves=0
                restart()
        print "Success obtained in %d tries"%(tries)
    

    I don’t understand what you’re trying to do here. It seems like you’re calling restart every time you find a 0 (i.e. an unvisited spot) on your board. But restart resets all board values to 0, so unless there’s some other way to fill the board with 1s before hitting this point, this will result in an infinite recursion. In fact, the mutual recursion between move and start might be able to achieve that in principle, but as it is, it’s way too complex! The problem is that there’s no clear recursion termination condition.

    def move(column,row):
        global x,y,a,moves
        try: b=a[x+row][y+column]
        except IndexError: return 0
        if b==0 and 0<=x+row<=7 and 0<=y+column<=7:
            x=x+row
            y=y+column
            a[x][y]=1
            moves+=1
            start()
        else: return 0
    

    Here, in principle, the idea seems to be that if your move hits a 1 or goes off the board, then the current branch of the recursion terminates. But because i and indexes are global above in start, when start is re-called, it re-shuffles indexes and resets i to 0! The result is sheer chaos! I can’t even begin to comprehend how that will effect the recursion; it seems likely that because i gets reset at the beginning of start every time, and because every successful call of move results in a call of start, the while loop in start will never terminate!

    I suppose it’s possible that eventually this process will manage to visit every square, at which point things might work as expected, but as it is, this is too complex even to predict.

    try :main()
    #except: print "I couldn't handle it" <-Row added to prevent python from returning a huge amount of errors
    

    Not sure what you mean by that last line, but it doesn’t sound like a good sign — you’re papering over an error instead of finding the root cause.

    I’m going to play with this code a bit and see if I can get it to behave marginally better by de-globalizing some of its state… will report back soon.

    Update:

    Ok I de-globalized indexes as described above. I then replaced the start/restart recursion with an infinite loop in restart, a return statement in start where the call to restart used to be, and a sys.exit() at the end of start (to break out of the infinite loop on success). The result behaves more as expected. This is still poor design but it works now, in the sense that it recursively tries a bunch of random paths until every local position has been visited.

    Of course it still doesn’t ever succeed; it just keeps looping. Actually finding a solution will probably require a lot more rethinking of this algorithm! But following my above suggestions should help some, at least.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Maybe you can help me with a problem I am having. The URL of
I found this problem all over the net but no answer yet, so maybe
I'd really like some help with the following MySQL / PHP problem (maybe bug?)
i am looking for opinions if the following problem maybe has a better/different/common solution:
Maybe someone found a workaround for the following problem: It seems as if AXIS
Maybe I'm just thinking about this too hard, but I'm having a problem figuring
Maybe world peace would be easier, but I have a problem with the widths
I am having a strange problem, maybe something to do with Apache more than
I meet a problem yesterday. Maybe it's because it is April 1st... but it
i'm having a problem to create a text_field without a method association. Maybe i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.