Lord_0069
Lord_0069

Reputation: 1

Sort the array as per the rules of card game using a generic method using only one loop

Input

cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen', "Jack", "Queen", "King"] 

Required Output

[2,3,5,6,8,'Jack','Queen','King']

I was able to sort it using this method, but i guess this isn't a one-loop only solution. does someone else have any guesses?

a= ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen','King','Jack','Queen']
for i in range(len(a)):
if a[i]=='Jack':
    a[i]=11
elif a[i]=='Queen':
    a[i]=12
elif a[i]=='King':
    a[i]=13
a.sort()

Upvotes: 0

Views: 43

Answers (2)

R. Baraiya
R. Baraiya

Reputation: 1530

Code:

cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
sorted(set(MyList), key = lambda x: cards.index(str(x)[0]))

Output:

[2, 3, 5, 6, 8, 'Jack', 'Queen', 'King']

Upvotes: 0

Samwise
Samwise

Reputation: 71522

Create a dict with values for the non-numeric cards, and use its get method to create a key function for sort/sorted.

>>> ranks = {'Jack': 11, 'Queen': 12, 'King': 13}
>>> cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen', "Jack", "Queen", "King"]
>>> sorted(cards, key=lambda c: ranks.get(c, c))
[2, 3, 5, 6, 8, 'Jack', 'Jack', 'Queen', 'Queen', 'King', 'King']

Upvotes: 2

Related Questions