代码之家  ›  专栏  ›  技术社区  ›  Ajinkya

3SUM使用python3和enumarate

  •  -1
  • Ajinkya  · 技术社区  · 6 年前

    我想在python3中使用“enumerate”解决以下任务

    下面演示枚举工作的方式

    nums=(2,7,1,15)               # a tuple  
    
    for num in enumerate(nums):
            print(num, 'hello')   
    
    #output
    #(0, 2) hello        #enumarate(nums) = (0,2)
    #(1, 7) hello
    #(2, 1) hello
    #(3, 15) hello      
    
    
    for count, num in enumerate(nums):
            print(num, 'hello')      
    
    # Output
    #2 hello    here count=0 but not displayed 
    #7 hello    here count=1 but not displayed
    #1 hello    here count=2 but not displayed
    #15 hello   here count=3 but not displayed
    

    使用上述原理,给定一个n个整数的数组num,num中是否有元素a、b、c,使a+b+c=目标和?在数组中查找所有唯一的三元组,得到和=目标和。

    目标和=10的解集是:

    [
      [0,1,2]             
    ]
    

    其中第0个索引的num+第1个索引的num+第2个索引的num(7+2+1=10)。

    2 回复  |  直到 6 年前
        1
  •  2
  •   dr jimbob    6 年前

    dict

    nums = [2, 7, 1, 2, 3]

    one_sum = {1: [2], 
               2: [0, 3], 
               3: [4],
               7: [1]}
    

    defaultdict one_sum = defaultdict(list) set

    enumerate

    for i, n in enumerate(nums):
        one_sum[n].append(i)
    

    two_sum

    two_sum = {3: [(0, 2), (2, 3)],
               4: [(2, 4)],
               5: [(0, 4), (3, 4)],
               8: [(1, 2)],
               9: [(0, 1), (1, 3)],
              10: [(1, 4)]}
    

    one_sum (2,2) (4,4) two_sum[4] nums[2] + nums[2]

    k target-k

    three_sum = [(0,1,2), (1,2,3)]
    
    # Note both were added from combining one_sum[1] with two_sum[9]
    # nothing from combining one_sum[2] with two_sum[8] as they reuse indexes
    # nothing from combining one_sum[3] as two_sum[7]==[]
    # nothing new from combining one_sum[7] with two_sum[3] as (0,1,2) and (1,2,3) already present.
    
        2
  •  0
  •   Ori Almog    6 年前

    def f(nums, target):
        sols = []
        for i1, n1 in enumerate(nums):
            for i2, n2 in enumerate(nums[i1+1:]):
                for i3, n3 in enumerate(nums[i2+1:]):
                    if (n1 + n2 + n3 == target):
                        sols.append([i1, i2, i3])
        return sols