Advertisement
Guest User

time_complexity.py

a guest
Dec 15th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. my_li = ['a', 'b', 'asdf', '9876']
  2.  
  3. for element in my_li:
  4.     print(f"Element: {element} has the index of {my_li.index(element)}")  # list.index() is O(n)
  5.  
  6. for element in my_li:
  7.     for element_2 in my_li:
  8.         if element_2 == element:
  9.             pass
  10.  
  11. for i, element in enumerate(my_li):
  12.     print(f"Element: {element} has the index of {i}")
  13.  
  14. my_dict = {'key': 1, "key2": "some val", "key3": "val"}
  15. print(my_dict['key'])  # O(1)
  16.  
  17. # time complexity O(n)
  18. if "key3" in my_dict.keys():
  19.     print("key3 in the dictionary")
  20. else:
  21.     print("key3 NOT in the dictionary")
  22.  
  23.  
  24. # time complexity O(1)
  25. try:
  26.     print(f"key3 with value of {my_dict['key3']} in the dictionary")
  27. except KeyError:
  28.     print("key3 NOT in the dictionary")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement