Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help with a call
#1
hi all,

I have a class which has a method which sort data in it. I need to create another method to check if data object I am dealing with is sorted or not. When I declare data object first it's not sorted. For checking whether this is sorted or not what I am doing is:
1) Create another data object and assigning original data object in it
2) Now sorting this new data object
3) Comparing newly created and sorted data object with original one

Problem I have is it's showing sorted as when I create a new data object and assign value of existing one in it and then sort this one, it' sorting original one also

def isOrdered(self):
        sortedDeck=self.deck
        sortedDeck.sort()
        for i in range(0, len(self.deck)):
            print(self.deck[i],sortedDeck[i])
Any idea why it would be happening?
Reply
#2
I haven't tested this, but it should work:
def is_ordered(self):
    deck = self.deck
    return all(deck[n] <= deck[n+1] for n in range(len(deck)-1))
Reply
#3
A variation that only supposes that self.deck is iterable
from itertools import tee

def is_ordered(self):
    t = tee(self.deck)
    next(t[1], None)
    return all(a <= b for a, b in zip(*t))
Reply
#4
Thanks everyone for the suggestion.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020