2

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

skrx
  • 18,183
  • 3
  • 28
  • 43
  • 1
    So show us what you have tried so far – dmitryro Jan 01 '18 at 01:02
  • if hands1[0]>hands1[1]: solitaireScore=5 if hands1[1]>hands1[2]: solitaireScore=10 – Simeon George Jan 01 '18 at 01:05
  • but the problem is I'm trying to make it like a nested if statement but don't know how to do it. I want to check if the first card is greater than the second card if this is true than proceed. to the other condition etc. – Simeon George Jan 01 '18 at 01:06
  • You might consider using dictionary like {"23":4, "24": 3, "12":2, "5": 1} and then if use sorted(your_dict) - like `sorted(yourdict.iteritems(), key=lambda (k,v): (v,k)) ` - using dictionary would give you O(1) time, vs using list – dmitryro Jan 01 '18 at 01:20
  • @dmitryro But sorting itself is `O(nlogn)`? – RoadRunner Jan 01 '18 at 01:58
  • Python's `sorted` function, applied to a collection, should not require implementing anything other than that, so time is not a real concern. – dmitryro Jan 01 '18 at 02:06

1 Answers1

2

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
Patrick Artner
  • 43,256
  • 8
  • 36
  • 57
  • also, can you help me solve a problem with writing to a list, every time I exit off the file and add more info it wipes the previous data? – Simeon George Jan 01 '18 at 01:24
  • @SimeonGeorge there are plenty of questions regarding "writing to file" for python on SO: https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python just as an example. Search them. Or read here: [reading-and-writing-files](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files) – Patrick Artner Jan 01 '18 at 01:27