help with a call - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: help with a call (/thread-22712.html) |
help with a call - PyPy - Nov-23-2019 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? RE: help with a call - Larz60+ - Nov-23-2019 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)) RE: help with a call - Gribouillis - Nov-24-2019 A variation that only supposes that self.deck is iterablefrom 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)) RE: help with a call - PyPy - Nov-24-2019 Thanks everyone for the suggestion. |