简体   繁体   English

计算列表中元素从0到n-1的总和,然后与最大的元素进行比较

[英]Calculate a sum of elements of the list from 0 to n-1 and compare with the largest one

I'm trying to write a code which will check, if a sum of some combination of elements of a given list is equal to the largest element in this list. 我正在尝试编写一个代码,该代码将检查给定列表元素的某种组合的总和是否等于此列表中的最大元素。 I wrote such a code: 我写了这样的代码:

def function(argument): 

  max_arg = max(argument)
  argument.remove(max_arg)
  for i in argument:

      if sum(argument[0:i+1]) == max_arg:
          return "true"
      else:
          return "false"

print function([1, 2, 3, 6])

I get the "false" string (which is an obvious mistake). 我得到“假”字符串(这是一个明显的错误)。 Could somebody please point out, what's wrong with the above presented code? 有人可以指出,上述代码有什么问题吗?

You are making several mistakes: 您正在犯几个错误:

  • You are confusing values with indices. 您正在将值与索引混淆。 The for loop gives you the values from the list , not indices into the list. for循环为您提供列表中 ,而不是列表中的索引。 Only because your values are integers does your loop not immediately break. 仅因为您的值是整数,循环才不会立即中断。

    In other words, i is not set to 0 , 1 , 2 , but to 1 , 2 and 3 . 换句话说, i没有被设置为012 ,但对123

  • You immediately return 'false' from the function when you found a combination that doesn't sum to the maximum. 当发现组合未达到最大总和时,您会立即从该函数返回'false' The first sum is 3 (value 1 then translates to sum(argument[0:2]) which produces 3 ), but you don't then let the loop continue. 第一个总和为3 (值1然后转换为sum(argument[0:2])产生3 ),但是您不要让循环继续。

To fix these mistakes, use a loop over the results of the range() function and only return 'false' when you tried all combinations: 要解决这些错误,请在range()函数的结果上使用循环,并在尝试所有组合时仅返回'false'

def function(argument): 
    max_arg = max(argument)
    argument.remove(max_arg)

    for i in range(len(argument)):
        if sum(argument[:i + 1]) == max_arg:
            return "true"
    return "false"

Your 'different combinations' are still pretty primitive. 您的“不同组合”仍然很原始。 You could try and produce all possible combinations of 3 numbers with itertools.combinations() and increasing lengths: 您可以尝试使用itertools.combinations()并增加长度来产生3个数字的所有可能组合:

from itertools import combinations

def function(argument): 
    max_arg = max(argument)
    argument.remove(max_arg)

    for length in range(1, len(argument) + 1):
        for combo in combinations(argument, length):
            if sum(combo) == max_arg:
                return "true"
    return "false"

Now the order in which your elements are arranged no longer matters; 现在,元素的排列顺序不再重要; [1, 4, 3, 2, 6] will return true because 1 + 3 + 2 produces 6. [1, 4, 3, 2, 6]将返回true,因为1 + 3 + 2产生6。

Demo: 演示:

>>> function([1, 2, 3, 6])
'true'
>>> function([1, 4, 3, 2, 6])
'true'
>>> function([1, 4, 3, 6])
'false'

You are always returning in the first loop itself, if the value is equal (which it wont be unless the first element is the largest element , you return "true" ) , otherwise you return "false" , instead do not return "False" immediately, only return "false" when you do not find any cases. 如果值相等(除非第一个元素是最大元素,否则将返回"true" ),否则始终返回第一个循环本身,否则返回"false" ,而不返回"False"立即,仅在找不到任何情况时才返回"false"

And you are using the values as indices, instead you want to enumerate over argument and use the index as indices 而且您正在使用值作为索引,而您想枚举argument并将索引用作索引

Example - 范例-

def function(argument): 
    max_arg = max(argument)
    argument.remove(max_arg)
    for i in range(len(argument)):
        if sum(argument[0:i+1]) == max_arg:
            return "true"
    return "false"

print function([1, 2, 3, 6])

Example/Demo - 示例/演示-

>>> def function(argument):
...     max_arg = max(argument)
...     argument.remove(max_arg)
...     for i in range(len(argument)):
...         if sum(argument[0:i+1]) == max_arg:
...             return "true"
...     return "false"
...
>>> print(function([1, 2, 3, 6]))
true
>>> print(function([1, 2, 3, 7]))
false

This performs the sum over elements only once: 这仅对元素执行一次求和:

def function(argument):  
  max_arg = max(argument)
  argument.remove(max_arg)
  s = 0
  for i in argument:
      s += i
      if s == max_arg:
          return "true"
  return "false"

Examples: 例子:

>>> function([1, 2, 3, 6])
'true'
>>> function([1, 2, 3, 7])
'false'
>>> function([1, 2, 3, 4, 6])
'true'

Keeping in mind that addition is associative and commutative... 请记住,加法是关联的和可交换的...

from itertools import permutations

def function(argument): 
    max_arg = max(argument)
    argument.remove(max_arg)

    for combo in permutations(argument):
        s = 0
        for element in combo:
            s = s + element
            if s == max_arg:
                return "true"
    return "false"

We see that we do not need to find all the possible combinations. 我们看到我们不需要找到所有可能的组合。 We can just find all the permutations of size (n-1) and add up elements until we find one that matches the max_arg . 我们可以找到所有大小为(n-1)的排列并添加元素,直到找到与max_arg匹配的max_arg

暂无
暂无

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

相关问题 找到 N*N 矩阵的最大成本路径,从 [0,0] 到 [N-1,N-1],并在一个方向上有偏好 - Find max cost path of N*N matrix, from [0,0] to [N-1,N-1] with perference in one direction 从N-1个样本计算最低Ave和STDEV - Calculate Lowest Ave and STDEV from N-1 Sample 列表中最大n个元素的项目和索引 - Items and index of largest n elements in a list 在列表中查找距离最小的 N 个最大元素 - Find N largest elements in a list with a minimum distance 遍历数组从数组中读取 n-1 个元素 - Iteration through an array reads n-1 elements from array A Function 以“N”为参数,执行元素的增加 N 次,然后减少(N-1)次,然后作为 Python 中的列表返回 - A Function take 'N' as argument, performs an Increase N times of Elements then decrease (N-1) times and then return as a list in the Python 找到一维数组/列表元素之间差异的函数,例如x [n] -x [n-1],x [n-2] -x [n-1]其中n是数组/列表的大小 - A function that finds the difference between elements of a 1D array/list e.g. x[n]-x[n-1], x[n-2]-x[n-1] where n is the size of the array/list 如何有效地从大小为n的列表中获取大小{n,n-1,n-2,... 1}的所有排列? - How to get all permutations of sizes {n, n-1,n-2, … 1} from list of size n efficiently? 如何对单个列表中的两个元素求和并与 integer 参数进行比较 - How to sum two elements from a single list and compare to an integer parameter 有没有办法对(1到n)求和并将其与总和(n+1到列表末尾)进行比较? - Is there any way to sum (1 to n) and compare it to the sum (n+1 to end of list)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM