I would like to get some feedback on my code. I am starting to program after doing a few online Python courses.
Would you be able to help me by following my track of thinking and then pinpointing where I could be more efficient? (I have seen other answers but they seem to be more complicated than they need to be, albeit shorter; but perhaps that is the point).
Question:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
fibValue = 0
valuesList = []
a = 0
b = 1
#create list
while fibValue <= 4000000:
fibValue = a + b
if fibValue % 2 == 0:
valuesList.append(fibValue)
a = b
b = fibValue
print (valuesList) #just so that I can see what my list looks like after fully compiled
print() #added for command line neatness
print() #added for command line neatness
newTot = 0
for i in valuesList:
newTot += i
print (newTot)
append()
isn't on the list of efficient ways to populate a list. Comprehensions are a means of accomplishing the same thing but more efficiently (in Python).squares = [ a**2 for a in range(2,100) ]
It's not quite so simple for Fibonacci, but the concept is worth using. \$\endgroup\$sum()
. \$\endgroup\$