不同元组元素的总和
我需要创建一个函数,这个函数可以接收一个元组列表和一个数字。举个例子:如果元组列表是 [(2,5),(8,9),(11,19),(22,43),(47,50)]
,而这个数字是14,那么它应该返回18。原因是,在这个数字13的情况下,列表中的数字是 2,3,4,5,8,9,11,12,13,14,15,16,17,18,19...
,如果把所有数字都包括进来,18就是最大的那个数字。
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18.
我现在有:
def converting(tuples,index):
values = [] #I will get [(2,3,4,5,6),(8,9),(11,12,13,14,15,16,17,18,19),(22,..,43),(47,48,49,50)]
for tuple in tuples:
tupleValues = range(tuple[0], tuple[1]+1)
values.extend(tupleValues) #ex(2,3,4,5,6)
if index <= len(values): #If 14 in the example is lower than len of the list, eg 42
return values[index-1] #return value of 14-1, which is 16?
print converting(14,[(2,5),(8,9),(11,19),(22,43),(47,50)])
当我打印这个的时候,我收到的信息是: for tuple in tuples: TypeError: 'int' object is not iterable
5 个回答
2
这一行代码可以正常运行:
>>> sorted(reduce(lambda x,y:x.union(set(y)), map(lambda r:range(r[0], r[1]+1), [(2,5),(8,9),(11,19),(22,43),(47,50)]), set()))[13]
18
在 [(47,50),(22,43),(8,9),(2,5),(11,19)]
这个列表中,元组的顺序已经不重要了。
3
这里有一些内容可以帮助你入门。虽然可以更简洁,但我尽量让它清晰易懂。你还应该考虑一下,如果给定的元组顺序不对,或者在值的列表中找不到索引时,你希望发生什么。
def valueAtIndex(tuples, index):
values = []
for tuple in tuples:
#range(start, finish) returns a list of integers starting at 'start' and ending at 'finish-1' e.g. range(0, 2) is [0, 1]
tupleValues = range(tuple[0], tuple[1]+1)
#Extend adds all of the elements from one list to the end of the other e.g. [0, 1, 2].extend(['a', 'b']) is [0, 1, 2, 'a', 'b']
values.extend(tupleValues)
if index <= len(values):
return values[index-1]
0
如果我理解得没错,你的问题是有一系列的区间,然后你需要从这些区间中提取第n个数字。这里有一个不同的解决方案,关于使用的算法。你只需要计算出在你的区间序列中缺失的所有数字,然后把这个数量加到你的值上:
tuples = [(2,5),(8,9),(11,19),(22,43),(47,50)]
#tuples = [(2,7),(9,14),(17,20)]
def result(tuple, value):
start = tuples[0][0] - 1
for idx in range(len(tuples) - 1):
if tuples[idx][1] >= value + start:
break
start = start + (tuples[idx+1][0] - tuples[idx][1] - 1)
return value + start
for i in range(1, 16):
print str(i) + ' ' + str(result(tuples, i))