Speed of loops
Of course, set is better suited for searching elements. It is based on hashes, so you can expect constant complexity most of the time. But what about iterating over all the object's elements? Let's compare the speed of loop iteration over the elements of list and set with pytest and pytest-benchmark. The pytest package has already been imported.
Bu egzersiz
Introduction to Testing in Python
kursunun bir parçasıdırEgzersiz talimatları
- Add
@benchmarkdecorator before the functions starting withiterate_. - Complete the loops in
iterate_listanditerate_set.
Uygulamalı interaktif egzersiz
Bu örnek kodu tamamlayarak bu egzersizi bitirin.
def test_list(benchmark):
# Add decorator here
@____
def iterate_list():
# Complete the loop here
____ in [i for i in range(1000)]:
pass
def test_set(benchmark):
# Add decorator here
____
def iterate_set():
# Complete the loop here
____ in {i for i in range(1000)}:
pass