在循环外举行Python条件?

时间:2016-12-15 15:51:23

标签: javascript python variables conditional-statements

所以,我在 Python 中学习了这个剖面搜索算法,并且我应用它来查找数字的近似平方根。至于算法,它可以很好地适应它的局限性,但是,我经常在 JavaScript 中做的事情是在变量中封装条件,因此它更容易阅读,例如:

var isGreaterThanFive = num > 5;
if(isGreaterThanFive && otherConditions...)

虽然在JavaScript中执行此操作绝对正常,但在尝试使用Python执行此操作时,我的程序似乎进入无限循环。这是我在JavaScript中的代码:

function sqrtOf (x) {
  var min = 0
  var max = x
  var epsylon = 0.001
  var guess = (max + min) / 2 
  var guessNumber = 0;

  //I created these two so it is easier to understand
  var notCloseEnough = Math.abs(Math.pow(guess, 2) - x) >= epsylon;
  var stillPlausible = guess <= x;

  while (notCloseEnough && stillPlausible) {
    guessNumber += 1

    if(Math.abs(Math.pow(guess, 2)) > x) {
      max = guess;
    } else {
      min = guess;
    }

    guess = (max + min) / 2;
  }

  return guess;
}

console.log(sqrtOf(25)); // 5

现在用Python:

def sqrtOf (x)
  minVal = 0
  maxVal = x
  epsylon = 0.001
  guess = (maxVal + minVal) / 2.0 
  guessNumber = 0;

  notCloseEnough = abs(guess ** 2 - x) >= epsylon
  stillPlausible = guess <= x

  while notCloseEnough and stillPlausible:
    guessNumber += 1

    if abs(guess ** 2) > x:
        maxVal = guess
    else:
        minVal = guess

    guess = (maxVal + minVal) / 2.0

  return guess

print sqrtOf(25)

2 个答案:

答案 0 :(得分:1)

当你写

notCloseEnough = abs(guess ** 2 - x) >= epsylon

您评估了语句abs(guess ** 2 - x) >= epsylon并将其结果分配给notCloseEnough。之所以再次进行计算只是因为您碰巧在代码中稍后引用了它的结果。

如果您想要重新评估事物,则需要一个函数对象。您可以定义一个内部函数,该函数可以看到外部函数的局部变量。

def sqrtOf (x):
  minVal = 0
  maxVal = x
  epsylon = 0.001
  guess = (maxVal + minVal) / 2.0 
  guessNumber = 0

  def notCloseEnough():
    return abs(guess ** 2 - x) >= epsylon

  def stillPlausible():
    return guess <= x

  while notCloseEnough() and stillPlausible():
    guessNumber += 1

    if abs(guess ** 2) > x:
        maxVal = guess
    else:
        minVal = guess

    guess = (maxVal + minVal) / 2.0

  return guess

print sqrtOf(25)

答案 1 :(得分:1)

这也很好,stillPlausible让我很困惑。输入应该在循环之前得到验证。

def sqrtOf(x):
  minVal = 0
  maxVal = x
  epsylon = 0.001
  guess = (maxVal + minVal) / 2.0
  guessNumber = 0;
  def trytrytry():
    while True:
      yield (abs(guess ** 2 - x) < epsylon, guess - x < epsylon)

  for (closeEnough, stillPlausible) in trytrytry():
    if closeEnough or not stillPlausible:
      break
    guessNumber += 1

    if abs(guess ** 2) > x:
        maxVal = guess
    else:
        minVal = guess

    guess = (maxVal + minVal) / 2.0

  return guess

print sqrtOf(25)