vendredi 17 mai 2019

Python: Comparing lists with conditional statements

I have tried an exercise where it wants me to return True if a list is sorted in ascending order and return False otherwise. List1 is supposed to return True, and List2 is supposed to return False.

I tried creating a new variable called sort to use the sort method to order it and compare it with an unmodified list and using a for loop to check whether the elements in the sorted list and unmodified list match one another in the same order. I'm not too sure how to tackle this problem correctly as I get False returns for both.

def is_sorted(t):
    sort = t.sort()
    for element in t:
        if t == sort:
            return True
        else:
            return False

def main():
    list1 = [1,2,2]
    print(is_sorted(list1))
    list2 = ['b', 'a']
    print(is_sorted(list2))

main()

Aucun commentaire:

Enregistrer un commentaire