简体   繁体   English

查找给定元组的列表的索引号

[英]Find index number of a list given a tuple

The input in the first parameter which is a list should add up to the second parameter which is an integer.作为列表的第一个参数中的输入应该与作为整数的第二个参数相加。 using only two numbers inside the list only once and returning the index of only one pair of numbers.只使用列表中的两个数字一次,并且只返回一对数字的索引。 So the approach i took here using the itertools module is to make possible unique combinations of ints which i can use to add up the numbers to the second parameter.所以我在这里使用 itertools 模块采取的方法是使整数的唯一组合成为可能,我可以用它来将数字与第二个参数相加。 but the combination is giving me a tuple inside a loop.但组合给了我一个循环内的元组。 which i can't use inside the list.我不能在列表中使用。 Is there a way to check if the values inside the tuple which is 'i' inside the last 'if' block exist inside the list.有没有办法检查列表中是否存在最后一个“if”块中的“i”元组中的值。 If so, then how can i return the indexes of the expected output from the list in the first parameter.如果是这样,那么我如何从第一个参数的列表中返回预期输出的索引。 At this point, i'm kinda stuck here and the answer might be obvious but what am i missing.在这一点上,我有点卡在这里,答案可能很明显,但我错过了什么。

Input: ([1,2,3,5,6], 5)输入:([1,2,3,5,6], 5)

from itertools import combinations
def twoSum(nums,target):

    a = list(nums)
    for i in combinations(a,2):
        if sum(i) == target and sum(i) in a:
            enumerate(a[i])

Expected output: [1, 2]预期输出:[1, 2]

Using itertools.combinations is slow, you could do this instead:使用itertools.combinations很慢,你可以这样做:

def twoSum(nums, target):
    lookup = {target - e: i for i, e in enumerate(nums)}
    return next((lookup[e], i) for i, e in enumerate(nums) if e in lookup)


res = twoSum([1, 2, 3, 5, 6], 5)
print(res)

Output输出

(2, 1)

The time complexity of this approach is O(n).这种方法的时间复杂度是 O(n)。 This returns only one pair.这仅返回一对。

The idea is to create a dictionary that maps the difference between the target and an element of nums to it's index.这个想法是创建一个字典,将targetnums元素之间的差异映射到它的索引。 Then if an element of nums is in lookup it means that those values add up to target, and therefore you can return their indexes.然后,如果nums的元素在lookup则意味着这些值加起来为目标,因此您可以返回它们的索引。

Not really clear what the OP is after, as there are multiple attempts to this question.不太清楚 OP 的目的是什么,因为对这个问题有多次尝试。 My interpretation would give the same answer that Dani Mesejo posted .我的解释会给出与Dani Mesejo 发布的相同的答案。 Here is another interpretation.这是另一种解释。

def twoSum(nums, target):
    return [i for i, x in enumerate(nums) if (target-x) in nums]

This returns all indices of elements in nums which sum up to target .这将返回nums中元素的所有索引,其总和为target So with you example, where this is only one valid pair所以以你为例,这只是一对有效的

>>> nums = [1, 2, 3, 5, 6]
>>> twoSum(nums, 5)
[1, 2]

but if there are more pairs, you get all the indices in the same list但是如果有更多对,你会得到同一个列表中的所有索引

>>> nums = [1, 2, 3, 4, 5, 6]
>>> twoSum(nums, 5)
[0, 1, 2, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM