So I have a list hand
whose data is something like this ['AS', 'AD', 'AC', 'CH', 'CS']
. Now I have to find the first character of each element in the list and see if there are 3 identical letters and 2 identical letters or not.
Note: they must all be in order though.. like always x,x,x,y,y or y,y,x,x,x. Any other combination, like x,y,y,x,x or x,y,x,y,x, will return False
So for example
['AS', 'AD', 'AC', 'CH', 'CS']
returns True
because there are 3 A and 2 C.
['AS', 'SD', 'SC', 'CH', 'CS']
returns False
because the order is not right
['CS', 'CD', 'AC', 'AH', 'AS']
returns True
because there are 3 A and 2 C
['AS', 'CD', 'DC', 'AH', 'CS']
returns False
because none of the characters appear 3 times and 2 times.
Here is my code so far, which doesn't work...
hand = ['AS', 'AD', 'AC', 'CH', 'CS']
updated_hands = list([x[1] for x in hand])
if ((updated_hands[0] == updated_hands[1] == updated_hands[2]) or (updated_hands[2] == updated_hands[3] == updated_hands[4])) and ((updated_hands[3] == updated_hands[4]) or (updated_hands[0] == updated_hands[1])):
print('True')
else:
print('False')
What changes should I make to this?
CodePudding user response:
Here is something that should work for arbitrary lengths and orders:
hands = [['AS', 'AD', 'AC', 'CH', 'CS']]
hands.append(['AS', 'SD', 'SC', 'CH', 'CS'])
hands.append(['CS', 'CD', 'AC', 'AH', 'AS'])
hands.append(['AS', 'CD', 'DC', 'AH', 'CS'])
for hand in hands:
condition = True
last_count = 1
last_item = hand.pop(0)[0]
while hand:
item = hand.pop(0)
if (item[0] == last_item):
last_count = 1
if (last_item != item[0]):
if (last_count == 2) or (last_count == 3):
condition = True
else:
condition = False
break
last_item = item[0]
print(condition)
Outputs:
True
False
True
False
CodePudding user response:
This is the approach I would take, which is effectively the same as what you've tried but I've just expanded it a bit to try and make it more readable. I think probably what you've got is "correct", but the complexity of doing it as a one liner is hiding a small bug.
def test_list(hand):
test1 = all(let[0] == hand[0][0] for let in hand[:3])
test2 = all(let[0] == hand[0][0] for let in hand[:2])
test3 = all(let[0] == hand[2][0] for let in hand[2:])
test4 = all(let[0] == hand[3][0] for let in hand[3:])
if (test1 and test3) or (test2 and test4):
print("True")
else:
print("False")
hand1 = ['AS', 'AD', 'AC', 'CH', 'CS']
hand2 = ['AS', 'SD', 'SC', 'CH', 'CS']
hand3 = ['CS', 'CD', 'AC', 'AH', 'AS']
hand4 = ['AS', 'CD', 'DC', 'AH', 'CS']
test_list(hand1) #prints True
test_list(hand2) #prints False
test_list(hand3) #prints True
test_list(hand4) #prints True