我在互联网上遇到一些实践问题,申请实习并结业。问题是相同的连续数字求和。
示例:[1,1,3,4,4,5] ---> [2,3,8,5]
def sum_consecutive(s):
p = []
for i in range(len(s)):
if s[i] == s[i-1]:
p.append(s[i] + s[i-1])
p.remove(s[i])
elif s[i] != s[i-1]:
p.append(s[i])
return p
在[1,4,4,4,0,4,3,3,1]上运行上述代码时,它应该返回[1,12,0,4,6,1]而不是
sum_conecutive(s)
if s[i] == s[i-1]:
p.append(s[i] + s[i-1])
p.remove(s[i]) #This line is the problem
elif s[i] != s[i-1]:
p.append(s[i])
错误:
ValueError: list.remove(x): x not in list
答案 0 :(得分:5)
使用变量来跟踪最后看到的值,然后将其添加到当前索引(如果相同)。
def sum_consecutive(s):
p = s[:1] # final list
cur = s[0] # keep track of last seen value
for i in s[1:]: # your exercise: replace this with `range`
if i == cur:
p[-1] += i
else:
p.append(i)
cur = i
return p
sum_consecutive([1, 4, 4, 4, 0, 4, 3, 3, 1])
# [1, 12, 0, 4, 6, 1]
作为奖励,请不要忘记stdlib存在,因此您可以使用itertools.groupby
在一行中完成此操作。
from itertools import groupby
[sum(g) for _, g in groupby([1, 4, 4, 4, 0, 4, 3, 3, 1])]
# [1, 12, 0, 4, 6, 1]
答案 1 :(得分:2)
def sum_consecutive(input_list):
i = 0
res = []
while(i < len(input_list)):
j = i
while(j < len(input_list) and input_list[i]==input_list[j]):
j = j + 1
res.append(input_list[i]*(j-i))
i = j
return res
答案 2 :(得分:0)
我写了这个功能,它很有趣,因为它很容易理解:
def count_occ(L):
p = []
count = 1
for i, j in zip(L[:-1], L[1:]):
if i != j:
p.append(count*i)
count = 1
else:
count += 1
p.append(count*L[-1])
return p