リスト内で互いに隣り合っている1(または私が望む任意の要素)の最大量を調べるにはどうすればよいですか?この場合Python 3:リスト内の最大要素が同じであることを確認してください
l = [2, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 7, 1, 1, 1]
私は4
ありがとう返す関数が必要になります。
リスト内で互いに隣り合っている1(または私が望む任意の要素)の最大量を調べるにはどうすればよいですか?この場合Python 3:リスト内の最大要素が同じであることを確認してください
l = [2, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 7, 1, 1, 1]
私は4
ありがとう返す関数が必要になります。
groupby()関数は、このために使用することができます。
import itertools
l = [2, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 7, 1, 1, 1]
print(max([len(list(g))*k for k, g in itertools.groupby(l, lambda x: x == 1)]))
隣接する '7 'が10個ある場合はどうなりますか?あなたは 'max 'する前にグループをフィルタリングする必要があります。 –
手動:
def makeMyHomework(li):
'''reads a list of int's and looks for the logest run of one int'''
curVal = None
curCount = 0
maxVal = None
maxCount = -1
for n in l:
if curVal == None:
curVal = n
if curVal == n:
curCount +=1
if curVal != n:
if curCount > maxCount: # check if current run > max so far
maxVal = curVal # store new max value
maxCount = curCount # store new max count
curVal = n # init the act ones
curCount = 1 # -"-
# print (n, ":", curVal, curCount, maxVal,maxCount)
# edge case - the max list is the last run
if curCount > maxCount:
maxVal = curVal
maxCount = curCount
return (maxVal, maxCount) # tuple of (value, number of occurences)
l = [2, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 7, 1, 1, 1,2,2,2,2,2]
print(makeMyHomework(l))
makeMyHomework thats great name;)))))))))) –
一つの可能な解決策は、 'itertools.groupby'を使用して、最高の数とグループを見つけることです1s。 –
誰かがすでに良い答えを出してくれましたが、あなたが何を試したのかは不思議です。 –