1D N Queens Array (Python) Solve function












-1















I know N_Queens is a very well covered topic, but i've to find a good python solution which uses a 1D array (and importantly, solves via filling the 1d array and then via function transforms this into a 2d array).



I've got so far as completing the (what I think i made far too complex) print and check function, but I seem to be unable to complete the solve function.



global queens
queens =

def printQ():
for i in queens:
for row in range(8):
if row == i:
print(" Q",end="")
else:
print(" .",end="")
print(" ")

def solve(x):
step = len(queens)
for indices in range(step):
if (x == queens[indices]):
return False
for i in range(step,0,-1):
if (x == queens[0-i]-i) or (x == queens[0-i]+i):
return False
else:
return True


def complete():
for i in range(8):
if solve(i) == True:
queens += [i]
elif solve(i) == False:
queens = queens - [i]
else:
return


Im trying to iterate through a list and place elements in global [queens] if possible. Each time I try to alter complete(), i either get an empty list or an error. I am trying to solve this via backtracking, but i'm unsure how exactly my psuedo-code should look for complete()



Any advice would be greatly appreciated, and apologies if my code isn't high-quality, very much still a beginner.



note: To prove both functions work, simply add items to the array [1,4,2] for example.










share|improve this question




















  • 1





    A brief look at this shows that your indentation is incorrect. As you know, in python indentation influences the meaning of the code. Please first correct this.

    – trincot
    Jan 20 at 10:12











  • Hi, I formatted this in a separate app (CodeBeautify) because when i placed it in the text it didnt paste as a block of code. I will manually re-indent now. Apologies.

    – philcode101
    Jan 20 at 10:27











  • There is no recursion in complete. It optimistically performs 8 iterations, sometimes adding an index, sometimes removing it. So at the end you'll not have 8 queens. The backtracking and recurring is missing from your algorithm. I would suggest to look into other solutions (that abound on the internet) and pick up how recursion/backtracking is used. Even if they would use a 2D representation it is still key to the solution with 1D as well.

    – trincot
    Jan 20 at 10:39
















-1















I know N_Queens is a very well covered topic, but i've to find a good python solution which uses a 1D array (and importantly, solves via filling the 1d array and then via function transforms this into a 2d array).



I've got so far as completing the (what I think i made far too complex) print and check function, but I seem to be unable to complete the solve function.



global queens
queens =

def printQ():
for i in queens:
for row in range(8):
if row == i:
print(" Q",end="")
else:
print(" .",end="")
print(" ")

def solve(x):
step = len(queens)
for indices in range(step):
if (x == queens[indices]):
return False
for i in range(step,0,-1):
if (x == queens[0-i]-i) or (x == queens[0-i]+i):
return False
else:
return True


def complete():
for i in range(8):
if solve(i) == True:
queens += [i]
elif solve(i) == False:
queens = queens - [i]
else:
return


Im trying to iterate through a list and place elements in global [queens] if possible. Each time I try to alter complete(), i either get an empty list or an error. I am trying to solve this via backtracking, but i'm unsure how exactly my psuedo-code should look for complete()



Any advice would be greatly appreciated, and apologies if my code isn't high-quality, very much still a beginner.



note: To prove both functions work, simply add items to the array [1,4,2] for example.










share|improve this question




















  • 1





    A brief look at this shows that your indentation is incorrect. As you know, in python indentation influences the meaning of the code. Please first correct this.

    – trincot
    Jan 20 at 10:12











  • Hi, I formatted this in a separate app (CodeBeautify) because when i placed it in the text it didnt paste as a block of code. I will manually re-indent now. Apologies.

    – philcode101
    Jan 20 at 10:27











  • There is no recursion in complete. It optimistically performs 8 iterations, sometimes adding an index, sometimes removing it. So at the end you'll not have 8 queens. The backtracking and recurring is missing from your algorithm. I would suggest to look into other solutions (that abound on the internet) and pick up how recursion/backtracking is used. Even if they would use a 2D representation it is still key to the solution with 1D as well.

    – trincot
    Jan 20 at 10:39














-1












-1








-1








I know N_Queens is a very well covered topic, but i've to find a good python solution which uses a 1D array (and importantly, solves via filling the 1d array and then via function transforms this into a 2d array).



I've got so far as completing the (what I think i made far too complex) print and check function, but I seem to be unable to complete the solve function.



global queens
queens =

def printQ():
for i in queens:
for row in range(8):
if row == i:
print(" Q",end="")
else:
print(" .",end="")
print(" ")

def solve(x):
step = len(queens)
for indices in range(step):
if (x == queens[indices]):
return False
for i in range(step,0,-1):
if (x == queens[0-i]-i) or (x == queens[0-i]+i):
return False
else:
return True


def complete():
for i in range(8):
if solve(i) == True:
queens += [i]
elif solve(i) == False:
queens = queens - [i]
else:
return


Im trying to iterate through a list and place elements in global [queens] if possible. Each time I try to alter complete(), i either get an empty list or an error. I am trying to solve this via backtracking, but i'm unsure how exactly my psuedo-code should look for complete()



Any advice would be greatly appreciated, and apologies if my code isn't high-quality, very much still a beginner.



note: To prove both functions work, simply add items to the array [1,4,2] for example.










share|improve this question
















I know N_Queens is a very well covered topic, but i've to find a good python solution which uses a 1D array (and importantly, solves via filling the 1d array and then via function transforms this into a 2d array).



I've got so far as completing the (what I think i made far too complex) print and check function, but I seem to be unable to complete the solve function.



global queens
queens =

def printQ():
for i in queens:
for row in range(8):
if row == i:
print(" Q",end="")
else:
print(" .",end="")
print(" ")

def solve(x):
step = len(queens)
for indices in range(step):
if (x == queens[indices]):
return False
for i in range(step,0,-1):
if (x == queens[0-i]-i) or (x == queens[0-i]+i):
return False
else:
return True


def complete():
for i in range(8):
if solve(i) == True:
queens += [i]
elif solve(i) == False:
queens = queens - [i]
else:
return


Im trying to iterate through a list and place elements in global [queens] if possible. Each time I try to alter complete(), i either get an empty list or an error. I am trying to solve this via backtracking, but i'm unsure how exactly my psuedo-code should look for complete()



Any advice would be greatly appreciated, and apologies if my code isn't high-quality, very much still a beginner.



note: To prove both functions work, simply add items to the array [1,4,2] for example.







python backtracking n-queens






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 20 at 10:29







philcode101

















asked Jan 20 at 10:03









philcode101philcode101

185




185








  • 1





    A brief look at this shows that your indentation is incorrect. As you know, in python indentation influences the meaning of the code. Please first correct this.

    – trincot
    Jan 20 at 10:12











  • Hi, I formatted this in a separate app (CodeBeautify) because when i placed it in the text it didnt paste as a block of code. I will manually re-indent now. Apologies.

    – philcode101
    Jan 20 at 10:27











  • There is no recursion in complete. It optimistically performs 8 iterations, sometimes adding an index, sometimes removing it. So at the end you'll not have 8 queens. The backtracking and recurring is missing from your algorithm. I would suggest to look into other solutions (that abound on the internet) and pick up how recursion/backtracking is used. Even if they would use a 2D representation it is still key to the solution with 1D as well.

    – trincot
    Jan 20 at 10:39














  • 1





    A brief look at this shows that your indentation is incorrect. As you know, in python indentation influences the meaning of the code. Please first correct this.

    – trincot
    Jan 20 at 10:12











  • Hi, I formatted this in a separate app (CodeBeautify) because when i placed it in the text it didnt paste as a block of code. I will manually re-indent now. Apologies.

    – philcode101
    Jan 20 at 10:27











  • There is no recursion in complete. It optimistically performs 8 iterations, sometimes adding an index, sometimes removing it. So at the end you'll not have 8 queens. The backtracking and recurring is missing from your algorithm. I would suggest to look into other solutions (that abound on the internet) and pick up how recursion/backtracking is used. Even if they would use a 2D representation it is still key to the solution with 1D as well.

    – trincot
    Jan 20 at 10:39








1




1





A brief look at this shows that your indentation is incorrect. As you know, in python indentation influences the meaning of the code. Please first correct this.

– trincot
Jan 20 at 10:12





A brief look at this shows that your indentation is incorrect. As you know, in python indentation influences the meaning of the code. Please first correct this.

– trincot
Jan 20 at 10:12













Hi, I formatted this in a separate app (CodeBeautify) because when i placed it in the text it didnt paste as a block of code. I will manually re-indent now. Apologies.

– philcode101
Jan 20 at 10:27





Hi, I formatted this in a separate app (CodeBeautify) because when i placed it in the text it didnt paste as a block of code. I will manually re-indent now. Apologies.

– philcode101
Jan 20 at 10:27













There is no recursion in complete. It optimistically performs 8 iterations, sometimes adding an index, sometimes removing it. So at the end you'll not have 8 queens. The backtracking and recurring is missing from your algorithm. I would suggest to look into other solutions (that abound on the internet) and pick up how recursion/backtracking is used. Even if they would use a 2D representation it is still key to the solution with 1D as well.

– trincot
Jan 20 at 10:39





There is no recursion in complete. It optimistically performs 8 iterations, sometimes adding an index, sometimes removing it. So at the end you'll not have 8 queens. The backtracking and recurring is missing from your algorithm. I would suggest to look into other solutions (that abound on the internet) and pick up how recursion/backtracking is used. Even if they would use a 2D representation it is still key to the solution with 1D as well.

– trincot
Jan 20 at 10:39












1 Answer
1






active

oldest

votes


















1














If you are changing global variable from a function you need to mark it as global, otherwise, function will treat that variable as local. That is what you get. You get empty queens list in your complete function. Please notice you can reference global (like you do it in printQ and solve functions, but if you going to change it (like you have in your complete function) you have to mark it as global. Here is an example of how to do it.
Also you don't need to mark it as global on module level (first line in your code) it has to be on a function level



def complete():
global queens
for i in range(8):
if solve(i) == True:
queens += [i]
elif solve(i) == False:
queens = queens - [i]
else:
return





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54275342%2f1d-n-queens-array-python-solve-function%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    If you are changing global variable from a function you need to mark it as global, otherwise, function will treat that variable as local. That is what you get. You get empty queens list in your complete function. Please notice you can reference global (like you do it in printQ and solve functions, but if you going to change it (like you have in your complete function) you have to mark it as global. Here is an example of how to do it.
    Also you don't need to mark it as global on module level (first line in your code) it has to be on a function level



    def complete():
    global queens
    for i in range(8):
    if solve(i) == True:
    queens += [i]
    elif solve(i) == False:
    queens = queens - [i]
    else:
    return





    share|improve this answer




























      1














      If you are changing global variable from a function you need to mark it as global, otherwise, function will treat that variable as local. That is what you get. You get empty queens list in your complete function. Please notice you can reference global (like you do it in printQ and solve functions, but if you going to change it (like you have in your complete function) you have to mark it as global. Here is an example of how to do it.
      Also you don't need to mark it as global on module level (first line in your code) it has to be on a function level



      def complete():
      global queens
      for i in range(8):
      if solve(i) == True:
      queens += [i]
      elif solve(i) == False:
      queens = queens - [i]
      else:
      return





      share|improve this answer


























        1












        1








        1







        If you are changing global variable from a function you need to mark it as global, otherwise, function will treat that variable as local. That is what you get. You get empty queens list in your complete function. Please notice you can reference global (like you do it in printQ and solve functions, but if you going to change it (like you have in your complete function) you have to mark it as global. Here is an example of how to do it.
        Also you don't need to mark it as global on module level (first line in your code) it has to be on a function level



        def complete():
        global queens
        for i in range(8):
        if solve(i) == True:
        queens += [i]
        elif solve(i) == False:
        queens = queens - [i]
        else:
        return





        share|improve this answer













        If you are changing global variable from a function you need to mark it as global, otherwise, function will treat that variable as local. That is what you get. You get empty queens list in your complete function. Please notice you can reference global (like you do it in printQ and solve functions, but if you going to change it (like you have in your complete function) you have to mark it as global. Here is an example of how to do it.
        Also you don't need to mark it as global on module level (first line in your code) it has to be on a function level



        def complete():
        global queens
        for i in range(8):
        if solve(i) == True:
        queens += [i]
        elif solve(i) == False:
        queens = queens - [i]
        else:
        return






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 20 at 10:39









        Vlad BezdenVlad Bezden

        29.3k10128114




        29.3k10128114
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54275342%2f1d-n-queens-array-python-solve-function%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Homophylophilia

            Updating UILabel text programmatically using a function

            Cloud Functions - OpenCV Videocapture Read method fails for larger files from cloud storage