-3

I've tried sorted, value_sort, all(a, b...zip), etc. but my function to check if the list is sorted, "is_solved" will not work. The function should check if the list of marbles is sorted in ascending order. I've commented out other approaches that I've tried that haven't worked. Any help would be most appreciated.

    def is_solved(self, list_of_marbles, i):
#returns true if the game is solved
        if self.list_of_marbles[i] < self.list_of_marbles[i+1]:   
        #all(self.list_of_marbles[i] <= self.list_of_marbles[i+1] for i 
        #in range(len(self.list_of_marbles)-1))
    #if self.is_solved(board2, i) == True:
    #if self.list_of_marbles[i] < self.list_of_marbles[i+1]:    
        return True
        else: 
            return False
JMatth
  • 121
  • 1
  • 3
  • 8
  • Also, `i` in the method `is_solved` is undefined. – Graipher Mar 04 '18 at 09:32
  • 1
    Possible duplicate of [Pythonic way to check if a list is sorted or not](https://stackoverflow.com/questions/3755136/pythonic-way-to-check-if-a-list-is-sorted-or-not) – Aran-Fey Mar 04 '18 at 09:33
  • I've updated to "is_solved". I am getting an error that i is undefined. How do I address this? I tried the methods in the post, "pythonic way to check if a list is sorted or not" and was not able to get those to work either. – JMatth Mar 04 '18 at 09:37
  • Why would you expect `i` to be defined inside the function? You're not defining it there nor passing it from where you call the function. The naive fix is `def is_solved(self, list_of_marbles, i):` and `if self.is_solved(board2, i) == True:` but I can't tell if the algorithm is right or wrong in general. – JJJ Mar 04 '18 at 09:41
  • Can you explain how to algorithm is wrong? – JMatth Mar 04 '18 at 09:44
  • Edited to focus code on just the is_solved function. – JMatth Mar 04 '18 at 10:07
  • How are you calling your function? Make sure not to omit i as it is an argument of your function. –  Mar 04 '18 at 10:11

2 Answers2

1
def check(list):
    if (list == sorted(list)):
        return True
    else:
        return False

li = [1,2,3,4,5]
check(li)

if list == sorted(list) means entered list is sorted already

0
def Sort(x):
L=sorted(x)
if x==L:
    return x
else:
    i=0
    for i in range (len(x)):
        if x[i] > x[i+1] :
            break

    unsortedPart = x[i:]
    R = RecursiveMin(unsortedPart)
    I = unsortedPart.index(R)

    for j in range (len(x)):
        if x[j] > R :
            del x[(I+i)]
            x.insert(j,R)
            break

    return Sort(x)

This is the code for sorting a list in python in ascending order using recursion. But if what you're looking for is a True/False answer for the list being sorted or not, then there's not must required of you.

def checkSorted(list):
   L = sorted(list)
   if list == L:
      return True
   else:
      return False