Simeon George
Simeon George

Reputation: 21

List sorted-Python card game

I have a card game that contains a list of cards in a players hand from top to bottom and I need to check up to what point the cards list break from the order of small to large(from top to bottom). I am not able to use any sort of GUI's.

For example, cards in players hand: 23 24 12 5-check for the fifth element in the list that is properly sorted 4 3 2 1

Upvotes: 2

Views: 379

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51683

Code commented for explanation reasons, hth:

cardsInHand = [23,24,25,23,27,4]  # all your cards

cardsInOrder = []                 # empty list, to be filled with in order cards
lastCard = None  

for card in cardsInHand:                  # loop all cards in hand
    if not lastCard or lastCard < card:       # if none taken yet or smaller
        cardsInOrder.append(card)                 # append to result
        lastCard = card                           # remember for comparison to next card
    else:                                     # not in order
        break                                     # stop collecting more cards into list 

print(cardsInOrder)               # print all

Output:

[23, 24, 25]

If you need the unordered part of your hand as well, you can get that by:

unorderedCards = cardsInHand[len(cardsInOrder):] # list-comp based length of ordered cards

Upvotes: 2

Related Questions