循环迭代中另外两个数字的比较

时间:2019-05-06 12:08:44

标签: python algorithm

假设有数字变量:a,b,c,d,e ...,我想先比较a和b,伪代码:

   if a > b:
       if a > b+c:
           if a > b+c+d:
               ...
           else:
               ...
       else:
           ...
   else:
       ...

一个接一个地前进,我不希望代码中有那么多if-else,有没有算法方法或简单的方法来实现?

4 个答案:

答案 0 :(得分:2)

如果从这些变量中列出一个列表,则可以将a与该列表的累加总和进行比较,并找到第一个索引为False的地方:

import numpy as np
b=1
c=2
d=7
e=10

a=8

x = [b,c,d,e]

np.argmin(np.greater(a,np.cumsum(x)))

尝试一下!

答案 1 :(得分:2)

您可以执行一个将两个值进行比较的函数,然后像这样使用它:

def compare_int(a, b):
    return a > b


def ur_func():
    a = 17
    b = 2
    c = 3
    d = 4
    e = 10
    # ...

    compare = 0
    x = [b, c, d, e]
    for value in x:
        compare += value
        if compare_int(a, compare):
            print str(a) + " is greater than " + str(compare)
        else:
            print str(compare) + " is greater than " + str(a)

答案 2 :(得分:1)

使用列表执行此操作的伪代码。请注意,这只是一个伪代码。您将不得不对其进行适当的修改以适合您的需求。

在以下解决方案中,我们尝试将所有参数添加到列表中。由于清单是有序的。我们可以选择参数,以便将其总和与a进行比较。

a = 1000
b = 10
c = 20
d = 30
e = 40

cmpr_params = [b,c,d,e]

for i in range(1, (len(cmpr_params)+1)):
    if a > sum(cmpr_params[:i]):
        print (" a is greater a = %s, sum = %s" %(a, sum(cmpr_params[:i])))
    else:
        print (" a is lesser a = %s, sum = %s" %(a, sum(cmpr_params[:i])))

输出:

 a is greater a = 1000, sum = 10
 a is greater a = 1000, sum = 30
 a is greater a = 1000, sum = 60
 a is greater a = 1000, sum = 100

如果将a的值更改为85,则输出将如下所示:

 a is greater a = 85, sum = 10
 a is greater a = 85, sum = 30
 a is greater a = 85, sum = 60
 a is lesser a = 85, sum = 100

答案 3 :(得分:1)

您可以尝试此操作并获取发生这种情况的索引

  <ItemGroup>
    <Content Include="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Include="appsettings.Development.json">
      <DependentUpon>appsettings.json</DependentUpon>
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>