How to add some values ​​that were created in a while loop using Python

I solved the Euler project problem , which is as follows:

Considering the members in the Fibonacci sequence, whose values ​​do not exceed four million, we find the sum of the even members. "

So, I used this script to print the Fibonacci sequence to four million:

a = 0 b = 1 while b < 4000000: print b a, b = b, a+b 

Obviously, I could run this and just manually add even values, but I would feel like I was cheating.

Technically, I assume I am asking two questions:

  • How can I choose Evenki?
  • How can I add these evens without assigning them to a variable?

Oh, and I'm sure this is very obvious, but I'm very new to ... well, programming in general, and I can easily get lost in the verbosity of experts. Thank you in advance!

+4
source share
3 answers

How can I choose the Evens?

Even numbers are those that leave a remainder of zero when you divide them by 2 (in integers). In Python, we get the "remainder after division as a whole" with the % operator.

However, there is another neat trick here. Even Fibonacci numbers are every third number in a sequence, and if you can strictly prove why, then you will be close to getting the formula needed to easily create a sequence of even Fibonacci numbers.

How can I add these evens without actually assigning them to a variable?

What is wrong if you assign them to a variable? Just set up another counter.

+1
source

If you do not agree with the purpose of the variables, you can use the functional approach :

 >>> from itertools import takewhile, ifilter >>> def fib(): a, b = 0, 1 while True: yield a a, b = b, a+b >>> def is_even(x): return x % 2 == 0 >>> sum(ifilter(is_even, (takewhile(lambda x: x<4000000, fib())))) 4613732 
+6
source

Ah, Project Euler!

This is more of a mathematical question than a programming question.

On the programming side, just add the battery. You can check for uniformity using the modulo % operator, which returns the integer remainder after dividing the left operand by the right operand.

 a, b = 0, 1 evens = 0 while b < 4000000: if not b%2: evens += b a, b = b, a+b 

As soon as you get the answer, Project Euler PDF and the forums will fill you with the matte part of this problem and really answer your questions. There are ways to avoid calculating each Fibonacci number and checking for uniformity, but this requires the use of specific mathematical properties of the Fibonacci sequence.

+2
source

Source: https://habr.com/ru/post/1387832/


All Articles