A: 在扑克牌游戏中, 需要实现一个查找顺子的算法:(连续的数字即为顺子), 随机发N张牌, 从中挑出最长的顺子, 并返回其长度, 如果没有顺子返回0. 现在手上的牌为[12,3,4,10,6,5,6,8,11,9,11,11,9,12,1].
m= [12,3,4,10,6,5,6,8,11,9,11,11,9,12,1]
m.sort()
s = set(m)
m1 = list(s)
def foo1(m1):
def foo(m1):
m = dict()
for i in range(len(m1)):
n=1
while 1:
if i+n >= len(m1):
break
elif m1[i+n] - m1[i] == n:
max_length = n+1
m['%s' % m1[i]] = max_length
n += 1
else:
break
return m
x = foo(m1)
cards = []
for key,value in x.items():
if max(x.values()) == 1:
return 0
elif value == max(x.values()):
cards.append([int(key)+i for i in range(max(x.values()))])
return '最长顺子为: %s, 长度为:%s' % (cards,max(x.values()))
print(foo1(m1))
结果如下:
最长顺子为: [[8, 9, 10, 11, 12]], 长度为:5