Python条件运算符'if else'不等于'and or' [英] Python conditional operator 'if else' not equal 'and or'

查看:124
本文介绍了Python条件运算符'if else'不等于'and or'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为下面两个函数的结果将是相同的,但事实并非如此。

  def fib2(n):
返回n并且n< 2或fib2(n-1)+ fib2(n-2)

def fib3(m):
如果m< 2 else fib3(m-1)+ fib3(m-2)

当参数值为4, fib2的输出为7,fib3的输出为3。为什么会发生这种情况?
我对此一无所知。

我的Python版本是2.7.9,操作系统是osX 10.11.1

解决方案

我试图变得更加冗长,编写您的函数,如下所示:

  def fib2(n) :
ret = n并且n< 2或fib2(n-1)+ fib2(n-2)
打印 fib2({})= {}。format(n,ret)
return ret

打印fib2(4)

def fib3(m):
ret = m,如果m < 2 else fib3(m-1)+ fib3(m-2)
打印 fib3({})= {}。format(m,ret)
return ret

打印fib3(4)

似乎是 fib2 尝试将布尔值添加到数字,这就是为什么它不正确的原因。 fib3 仅处理数字并且正确。但是请注意,这不是计算斐波纳契数的推荐方法!如果尝试使用fib3(1000),它将无限运行。最好从0和1开始,而不要使用递归来计算斐波那契数。 p>

  def fib4(n):
a = 0
b = 1
对于范围内的i ,n + 1):
a,b =(b,a + b)
返回a

打印fib4(0)
打印fib4(1)
打印fib4(2)
打印fib4(3)
打印fib4(4)
打印fib4(1000)

注意,它也适用于 n == 1000


I think below two function result will be same, but it is not.

def fib2(n):
  return n and n < 2 or fib2(n-1) + fib2(n-2)

def fib3(m):
  return m if m < 2 else fib3(m-1) + fib3(m-2)

When argument value is 4, fib2's output is 7, fib3's output is 3. Why this situation happen? I don't know about this.
My Python version is 2.7.9 and os is osX 10.11.1

解决方案

I tried to be more verbose and write your functions like this:

def fib2(n):
    ret = n and n < 2 or fib2(n-1) + fib2(n-2)
    print "fib2({}) = {}".format(n, ret)
    return ret

print fib2(4)

def fib3(m):
    ret = m if m < 2 else fib3(m-1) + fib3(m-2)
    print "fib3({}) = {}".format(m, ret)
    return ret

print fib3(4)

It appears that fib2 tries to add boolean values to numbers, and that's why it's not correct. fib3 handles only numbers and is correct. But notice that it's not a recommended way to calculate Fibonacci numbers! If you try fib3(1000) it will run infinitely. It's better to start from 0 and 1 upwards, and not use recursion to calculate Fibonacci numbers.

I wrote a short function that calculates Fibonacci number #n for you:

def fib4(n):
    a = 0
    b = 1
    for i in range(1, n + 1):
        a, b = (b, a + b)
    return a

print fib4(0)
print fib4(1)
print fib4(2)
print fib4(3)
print fib4(4)
print fib4(1000)

Notice it also works for n==1000.

这篇关于Python条件运算符'if else'不等于'and or'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆