EvilZone

Programming and Scripting => Beginner's Corner => : AnonymousCelt March 22, 2015, 10:24:27 PM

: [Python] [spoiler] Project Euler Question Two- Critique Please
: AnonymousCelt March 22, 2015, 10:24:27 PM

Task is to return the sum of all even fibonacci numbers below 4000000.

:

def ProblemTwo():

last = 1
current = 1
temp = 2
tally = 0

while current < 4000000:
temp = last + current
last = current
current = temp
if current % 2 == 0:
tally += current

print "My Answer is: %d" % tally




def main():
ProblemTwo()


if __name__ == '__main__':
main()


Any feedback is greatly appreciated.
: Re: [Python] [spoiler] Project Euler Question Two- Critique Please
: proxx March 23, 2015, 11:07:45 AM
Not wrong perse but why do you use a while and not a for loop ?
: Re: [Python] [spoiler] Project Euler Question Two- Critique Please
: AnonymousCelt March 23, 2015, 11:25:51 AM
Not wrong perse but why do you use a while and not a for loop ?
To be honest, because I was causing iteration within the loop and the variable was already defined I thought it would be best using the while loop as it only needs the check added.
Might be different in Python though (came from Java).
: Re: [Python] [spoiler] Project Euler Question Two- Critique Please
: Psycho_Coder March 23, 2015, 11:32:07 AM
Well tell you what you should really read about the numbers before coding it out. Bruteforcing isn't a good practice. You should carefully observe the stuff.

I will give you a simple hint with which you can improve your code.

Lets examine the Fibo series :-

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, .....


Do you observe something ?

What we observe is that every third number is even.

Well that's your hint for now.
: Re: [Python] [spoiler] Project Euler Question Two- Critique Please
: AnonymousCelt March 23, 2015, 08:16:58 PM
Well tell you what you should really read about the numbers before coding it out. Bruteforcing isn't a good practice. You should carefully observe the stuff.

I will give you a simple hint with which you can improve your code.

Lets examine the Fibo series :-

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, .....


Do you observe something ?

What we observe is that every third number is even.

Well that's your hint for now.


Ah, I get it.
For loop incrementing the fib sequence by 3 at a time, adding to the tally/total avoiding the need to verify whether it is even or not.
I posted this before receiving your feedback in the first project euler question. I'll look back into it all for a while before doing any more as I clearly have more to learn before I can benefit fully from the exercises.
: Re: [Python] [spoiler] Project Euler Question Two- Critique Please
: Psycho_Coder March 23, 2015, 08:30:18 PM
Alright. I will try to post some detailed answer on this. Maybe tomorrow.