I am attempting to generate a potential card ‘plays’ list from a predetermined hand of straights (in this game a straight is defined as 3+ cards – e.g. [3,4,5]). The difficlty lies in finding a way to take a list of identified straights (which may include multiple unconnected straights – ['2D','3D','4D','5D','6D','8D','9D','10D']) and appending them and their sub-straights contained within them to a plays list(for the given hand the output would ideally be [['2D','3D','4D'],['3D','4D','5D'],['4D','5D','6D'],['2D','3D','4D','5D'],['3D','4D','5D','6D'],['8D','9D','10D']])
Below is the current attempt being made;
seq = ['1D','2D','3D','4D', '6D', '7D','8D', '10D', '11D', '12D']
plays = []
for card in seq:
ind = seq.index(card)+1
try:
if int(seq[ind][0:len(seq[ind])-1]) - int(card[0:len(card)-1]) == 2:
for num in xrange(len(seq[0:ind])):
if len(seq[0:(ind-num)]) > 3:
plays.append(seq[0:(ind-num)])
plays.append(seq[num+1:ind])
elif len(seq[0:(ind-num)]) == 3:
plays.append(seq[0:(ind-num)])
print plays #debug
except IndexError:
print 'error'
#append from the last appended chunk up until last element?
#arises from final element
[[‘1D’, ‘2D’, ‘3D’, ‘4D’], [‘2D’, ‘3D’, ‘4D’], [‘1D’, ‘2D’, ‘3D’]]
[[‘1D’, ‘2D’, ‘3D’, ‘4D’], [‘2D’, ‘3D’, ‘4D’], [‘1D’, ‘2D’, ‘3D’], [‘1D’, ‘2D’, ‘3D’, ‘4D’, ‘6D’, ‘7D’, ‘8D’], [‘2D’, ‘3D’, ‘4D’, ‘6D’, ‘7D’, ‘8D’], [‘1D’, ‘2D’, ‘3D’, ‘4D’, ‘6D’, ‘7D’], [‘3D’, ‘4D’, ‘6D’, ‘7D’, ‘8D’], [‘1D’, ‘2D’, ‘3D’, ‘4D’, ‘6D’], [‘4D’, ‘6D’, ‘7D’, ‘8D’]**, [‘1D’, ‘2D’, ‘3D’, ‘4D‘], [‘6D’, ‘7D’, ‘8D’], [‘1D’, ‘2D’, ‘3D’]]
error
The ouput in bold indicates unwanted elements (duplicates or conjunction of separate straights).
Thanks for the input!
edit 1: added lines 10-12
edit 2: added solution provided by @Steve Tjoa
(Given that cards is a series of ints)
cards = [1, 2, 3, 4, 6, 7, 8, 10, 11, 12]
def f(cards):
for i in range(len(cards)):
for j in range(i+3, len(cards)+1):
if cards[i:j] == range(cards[i], cards[i]+j-i):
plays.append(cards[i:j])
print plays
Does this help?
Reasoning:
cards[i]is the first card of the straight;cards[j-1]is the last card.rangereturns consecutive integers.j-iis the length of the straight.