Upgrade to PRO for Only $50/Year—Limited-Time Offer! 🔥

Make your Big O smaller, complexity explained

Make your Big O smaller, complexity explained

Ever heard of big O and it sounded chinese/greek? Programmers that do not come from computer science do not know what this is. In this talk big O complexity is explained and displayed with examples in Python language how it can affect code execution. I give tips of how to make python code have better performance and why they they work.

Meili Triantafyllidi

February 21, 2019
Tweet

More Decks by Meili Triantafyllidi

Other Decks in Programming

Transcript

  1. O(n) - Linear complexity • 1 elements X time •

    2 elements 2X time • 10 elements 10X time • 100 elements 100X time
  2. O(n) - Linear complexity N Time N Time N Time

    Time = 3N Time = 0.5N Time = N
  3. O(n2) - Quadratic complexity • 1 elements X time •

    2 elements 4X time • 10 elements 100X time • 100 elements 10000X time
  4. O(n2) - Quadratic complexity • 1 elements X time •

    2 elements 4X time • 10 elements 100X time • 100 elements 10000X time ←100 slower than O(n)
  5. O(n2) - Quadratic complexity # Sequences of 2 for i

    in range(n): for k in range(n): print(i, k)
  6. O(n2) - Quadratic complexity # Sequences of 2 for i

    in range(n): for k in range(n): print(i, k) O(n)
  7. O(n2) - Quadratic complexity # Sequences of 2 for i

    in range(n): for k in range(n): print(i, k) O(n2)
  8. O(1) - constant complexity • 1 elements X time •

    2 elements X time • 10 elements X time • 100 elements X time
  9. O(1) - constant complexity • 1 elements X time •

    2 elements X time • 10 elements X time • 100 elements X time O(1)
  10. Context matters for i in range(n): if i in lst:

    print(i) vs for i in range(n): if i in d: print(i)
  11. Context matters for i in range(n): if i in lst:

    print(i) vs for i in range(n): if i in d: print(i) O(n)
  12. O(n2) Context matters for i in range(n): if i in

    lst: print(i) vs for i in range(n): if i in d: print(i)
  13. O(n2) Context matters for i in range(n): if i in

    lst: print(i) vs for i in range(n): if i in d: print(i) O(1)
  14. O(n) O(n2) Context matters for i in range(n): if i

    in lst: print(i) vs for i in range(n): if i in d: print(i)
  15. O(n) O(n2) Context matters for i in range(n): if i

    in lst: print(i) vs for i in range(n): if i in d: print(i) n=100 -> 100 slower !!!!!
  16. O(n2) Context matters do_a() # O(n) or O(1) do_b() #

    O(n) or O(1) do_c() # O(n2) No difference
  17. Common pitfall # list add/remove intermediate lst.pop(1) # O(n) lst.insert(10)

    # O(n) dict, set, frozenset, collections.deque, priority queue (heapq)
  18. Summary • Know your data structures ◦ set, dictionaries are

    our friends for lookups ◦ Lists are good for appends ◦ Search python complexity • Look for O(n) → O(1) where it reduces total complexity • Beware of hidden complexity in assignments