我开始使用python进行编程,现在将自己献给列表。有可能在python列表中找到带有参数的序列吗? 我的例子: 查找大于0的奇数序列,找到最长的一个并求和;如果有两个序列的长度相同,则输出将是总和更大的序列。 然后打印序列和总和的长度。
示例:
Input: - 5 0 10 13 2 4 6 5 - 13 1 2 4 5 8 10 12
Output:
3
30
(sequence 8, 10, 12)
谢谢!
答案 0 :(得分:0)
是的,有。
首先使用原始列表l
的第一个元素初始化列表:
longest = []
current_longest = []
然后创建一个for循环,该循环将扫描原始列表中的所有内容:
for el in l:
然后检查是否将任何内容添加到原始列表中:
if ! current_longest and el % 2 == 0:
current_longest = [el]
elif el % 2 == 0 and el == longest[-1] + 2:
current_longest.append(el)
else:
if len(current_longest) > longest or sum(longest) < sum(current_longest):
longest = current_longest
current_longest = []
这样的事情。
答案 1 :(得分:0)
您可以执行以下操作:
def ranges(lst):
beg = 0
for idx, elem in enumerate(lst):
# find the first even number
if elem % 2 == 0:
# yield the range of odd numbers
yield (beg, idx)
# set a new begin
beg = idx + 1
else:
# the last range
yield (beg, len(lst))
def rngLen(rng):
# a length of a range
return rng[1] - rng[0]
def findSum(lst):
rngs = list(ranges(lst))
# find the maximum range
max_range = max(map(rngLen, rngs))
# get all the ranges with the length = max_range
all_max_ranges = filter(lambda rg: rngLen(rg) == max_range, rngs)
# get the sums of all the max ranges
all_sums = map(lambda rg: sum(lst[rg[0]: rg[1]]), all_max_ranges)
# return the max len and sum
return max_range, max(all_sums)
答案 2 :(得分:0)
您的描述说的是奇数序列,但是您的结果显示偶数序列,因此这是使用enumerate
和iter
w / next
lst = [-5, 0, 10, 13, 2, 4, 6, 5, -13, 1, 2, 4, 5, 8, 10, 12]
res = []
for i, v in enumerate(lst):
a = iter(lst[i:])
b = next(a)
l = []
while not b % 2:
l.append(b)
try:
b = next(a)
except StopIteration:
break
if l:
res.append(l)
print(sorted(res, key=lambda x: (len(x),sum(x)), reverse = True)[0])
# [8, 10, 12]