There is a lost of waste in your code

- Code: Select all
`m=range(1,1001)`

m_squared=[]

for i in m:

if i**2 < 1001:

m_squared.append(i**2)

You are doing the same calcualtion twice (i**2) when it is a result you want to keep.

You throw away lots of results in the if condition.

- Code: Select all
`m = range(1, 1001)`

m_squared = []

wasted_loops = 0

for i in m:

if i ** 2 < 1001:

m_squared.append(i ** 2)

else:

wasted_loops += 1

print wasted_loops

- Code: Select all
`969`

969 calulations are done that are not wanted out of 1000

Compare this code

- Code: Select all
`squares = []`

i = 1

while True:

result = i * i

if result < 1001:

squares.append(result)

i += 1

else:

break

It only does the calculation once and only loops the neccessary times until it reaches greater then 1000

To prove that

- Code: Select all
`squares = []`

i = 1

loop_count = 0

while True:

result = i * i

if result < 1001:

squares.append(result)

i += 1

else:

break

loop_count += 1

print loop_count

- Code: Select all
`31`

But does it give the same result ?

- Code: Select all
`m = range(1, 1001)`

m_squared = []

for i in m:

if i ** 2 < 1001:

m_squared.append(i ** 2)

squares = []

i = 1

while True:

result = i * i

if result < 1001:

squares.append(result)

i += 1

else:

break

print m_squared == squares

- Code: Select all
`True`

Due to the reasons discussed

here we will be moving to

python-forum.io/ on October 1 2016

This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.