【问题标题】:How can i solve this? It regards the indexing and for loops我该如何解决这个问题?它涉及索引和 for 循环
【发布时间】:2018-10-25 21:08:39
【问题描述】:

编写一个以两个列表 (l1, l2) 作为参数的函数。这两个列表包含整数。 第二个列表包含 [0, len(l1)) 范围内的数字,这些数字表示 第一个列表。该函数必须返回 l1 中索引在 l2 中的元素的总和。 请注意,如果 l2 多次包含相同的索引,则您只需计算 l1 中的相应元素一次

例如:如果 l1 = [11, 2, 0, -3, 3] 和 l2 = [0, 1, 3, 0],则函数必须返回 10,因为 11 + 2 + (-3) = 10。

【问题讨论】:

  • 取决于语言
  • 一种方法是从第二个列表中删除所有重复项。然后遍历第二个列表,并为每个元素访问第一个列表的适当元素并将其添加到总和中。
  • 我需要挖掘我的 COBOL 书籍。

标签: list for-loop indexing parameters range


【解决方案1】:

在python中,

l2 = set(l2)
summation = sum([l1[i] for i in l2])

【讨论】:

    【解决方案2】:

    在 Perl 中,

    use List::Util qw(sum0 uniqnum);
    
    sub ($l1, $l2) {
        sum0 @$l1[uniqnum @$l2]
    }
    

    在 Haskell 中,

    fmap (fmap sum) (fmap (flip fmap nub) (fmap fmap (!!)))
    

    在 Haskell 中,

    {-# LANGUAGE ParallelListComp #-}
    \l1 l2 -> sum [ x * fromEnum (i `elem` l2) | x <- l1 | i <- [0 ..]]
    

    在 Python 中,

    lambda l1, l2: sum([l1[i] for i in range(len(l1)) if i in l2])
    

    在 C 中,

    #include <stddef.h>
    #include <stdbool.h>
    
    static bool h(const long *v, size_t n, long k) {
        return !n || *v != k && h(v + 1, n - 1, k);
    }
    
    static long g(const long *u, const long *w, size_t n, size_t c) {
        return c >= n ? 0 : h(w, c, w[c]) * u[w[c]] + g(u, w, n, c + 1);
    }
    
    static long f(const long *l1, const long *l2, size_t n) {
        return g(l1, l2, n, 0);
    }
    

    在 C 中,

    #include <stddef.h>
    #include <setjmp.h>
    
    static long f(const long *l1, const long *l2, size_t n) {
        volatile long r = 0;
        volatile size_t c = 0;
        jmp_buf d;
        setjmp(d);
        if (c >= n) return r;
        volatile size_t i = c;
        jmp_buf e;
        setjmp(e);
        if (!i--) r += l2[c][l1]; else
        if (l2[i] != c[l2]) longjmp(e, 0);
        c++;
        longjmp(d, 1);
    }
    

    【讨论】:

      【解决方案3】:

      在 Java 中:

      import java.util.HashSet;
      import java.util.List;
      import java.util.Set;
      
      public class SumList {
      
          public static Integer calcualteListSum(List<Integer> elements, List<Integer> indexes) {
              Set<Integer> uniqueIndexes = new HashSet<Integer>(indexes);
      
              Integer sum = 0;
              for(Integer index : uniqueIndexes) {
                  sum += elements.get(index);
              }
      
              return sum;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-04
        • 1970-01-01
        • 2020-03-25
        • 2020-02-14
        相关资源
        最近更新 更多