【问题标题】:scan list for a range of conditions一系列条件的扫描列表
【发布时间】:2015-10-29 23:47:57
【问题描述】:

拥有元素:

  • 数据列表:L
  • 目标值:目标
  • 界限:#一个正数
  • 方法:search_combination(data,target) 返回一个列表

我想把这些放在一个方法中,一遍又一遍地调用search_combination,并在满足条件时返回该方法的结果。 新方法首先在 search_combination 中尝试“target”(如果满足条件则返回结果),然后尝试 target+-range(bound) 并返回条件最接近目标的值。 主要问题是为尝试 target+-range(bound) 编写代码。

这是我的自动取款机:

def main(data,target,bound):
    result=search_combination(data,target)
    if result !=[]: #condition is met
       return [result,target]
    else:
       for i in range(bound):
           temp=i
           result=search_combination(data,target+temp)
           if result !=[]:
              temp=target+temp
              break
           result=search_combination(data,target-temp)
           if result !=[]:
              temp=target-temp
              break
       return [result,temp]

这段代码如何更好?

【问题讨论】:

    标签: python search conditional-statements limits


    【解决方案1】:

    如果你想改变 +/-,你可以这样做

       import math
    
       ...
    
       for i in range(bound):
           temp=i
           emptyFound = False
           for j in range(2):
             result=search_combination(data,target+(math.pow(-1, j) * temp))
             if result !=[]:
                emptyFound = True
                break
           if emptyFound == True:
             break;
       return [result,temp]
    

    【讨论】:

    • 感谢您的评论。但“bound”表示“与目标的最大距离”。并且 for 循环尝试“一次一步”,在每个步骤中尝试两个方向。如果这是有道理的。我正在寻找一种不需要复制代码行的更短的方法
    猜你喜欢
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多