Reputation: 11677
Let's say I have lists of letters from two players
player_1 = ['a', 'b', 'c', 'd', 'e']
player_2 = ['c', 'f', 'x', 'd', 'r']
I'd like to ensure that some submitted word can be constructed by alternating letters between the player_1
list and the player_2
list.
For example fax
is a valid word since that can be formed by alternating letters in the following way: P2, P1, P2. Red
also works since that can be formed by alternating letters in the same way, even though the letter "d" appears in both player_1
and player_2
's hand.
bad
does not work since it would require a: P1, P1, P2 combo, which does not alternate.
I'm trying to create a function validate_word
that validates that a word can be constructed in this way. Here is my initial attempt that gets a bit too convoluted:
from itertools import cycle
from itertools import chain, repeat
player_1 = ['a', 'b', 'c', 'd', 'e']
player_2 = ['c', 'f', 'x', 'd', 'r']
def validate_word(word):
sequence_list = []
for letters in word:
if letters in player_1 and letters in player_2:
sequence_list.append(3)
elif letters in player_1:
sequence_list.append(1)
elif letters in player_2:
sequence_list.append(2)
else:
sequence_list.append(0)
return sequence_list
So now we have a list that contains a number indicating whether a given letter appears in P1 hand, P2 hand, both of their hand (3), or neither of their hands (0). I was then going to make sure that those numbers cycled either from 1 -> 2 or 2 -> 1, but I'm not quite how to deal with 3s, or whether this is the most efficient way of handling this.
What's a better way of dealing with this?
Upvotes: 1
Views: 30
Reputation: 195468
You can combine itertools.cycle
and all()
to make sure the word can be constructed by alternating the two lists:
from itertools import cycle
def validate_word(p1, p2, w):
c1 = cycle([p1, p2])
c2 = cycle([p2, p1])
return all(ch in next(c1) for ch in w) or all(ch in next(c2) for ch in w)
player_1 = ['a', 'b', 'c', 'd', 'e']
player_2 = ['c', 'f', 'x', 'd', 'r']
print(validate_word(player_1, player_2, 'fax'))
print(validate_word(player_1, player_2, 'red'))
print(validate_word(player_1, player_2, 'bad'))
Prints:
True
True
False
Upvotes: 3