Variable assignment in expressions

后端 未结 4 1884
傲寒
傲寒 2021-01-16 13:36

Here is my code to generate values in the fibonnacci sequence below 10,000,000.

  3 fibs = [1,1]
  4 while((x = fibs[-1] + fibs[-2]) <= 10000000):
  5             


        
相关标签:
4条回答
  • 2021-01-16 14:07

    Basically:

    fibs = [1]
    x = 1
    
    while(x <= 10000000):
      fibs.append(x)
      # It is not possible for "fibs" not to have
      # at least two elements by now
      x = fibs[-1] + fibs[-2]
    

    (It was, in fact, one of the design goals of Python to avoid mixing expressions and assignments like C — that's why there's no x++, x--, which is also a semi-FAQ.)

    0 讨论(0)
  • 2021-01-16 14:24

    The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct.

    Please check http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm

    0 讨论(0)
  • 2021-01-16 14:29
    from functools import partial
    from itertools import imap, islice, takewhile
    import operator
    fibs = [1, 1]
    for x in takewhile(partial(operator.ge, 10000000),
                       imap(operator.add, fibs, islice(fibs, 1, None))):
        fibs.append(x)
    

    Oh wait, you said "simplest"? Nevermind then.

    0 讨论(0)
  • 2021-01-16 14:34

    In Python, assignment is not an expression, and therefore has no value.

    The simplest solution is to do the assignment in the first part of the loop:

    fibs=[1,1]
    while fibs[-1] <= 10000000:
       fibs.append(fibs[-1] + fibs[-2])
    
    0 讨论(0)
提交回复
热议问题