Rendition efficiency about while loop. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Rendition efficiency about while loop.

Why it takes so much longer to run the first set of code than the second? words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) while counter < max_index: word = words[counter] print(word + "!") counter = counter + 1 ------------------------------------------------------- words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1

3rd Jul 2018, 8:02 AM
aaron_He
2 Answers
+ 1
if you really want to timemeasure the code, you should use some reliable approaches like this (I excluded print operator to avoid I/O speed interfering): ==== import timeit s = """ words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) while counter < max_index: word = words[counter] counter = counter + 1 """ print(timeit.timeit(stmt=s, number=100000)) s1 = """ words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] counter = counter + 1 """ print(timeit.timeit(stmt=s1, number=100000)) ==== Both code snippets take the similar time to execute, with aceptable inaccuracy AND the second snippet is always slower btw due to additional calculations.
3rd Jul 2018, 9:26 AM
strawdog
strawdog - avatar
0
they both should run i a few ms. if you are comparing run times on sololearn playground, its dependant on all traffic on the site and your own connection.
3rd Jul 2018, 8:26 AM
Markus Kaleton
Markus Kaleton - avatar