1 of 17

CS111 – Fundamentals of CS�Lecture 13�Python IV�

2 of 17

Reading for this & last lectures

  1. Python Crash Course (Chapters 1 to 8 and 10)
  2. Share any useful resources you find
  3. https://www.freecodecamp.org/
  4. https://www.w3schools.com/python/default.asp

2

3 of 17

Lecture 10 Outline

  1. Merge Sort
  2. Ternary Operator
  3. Tuples
  4. More on Lists

3

4 of 17

Remember

  • Any fool can write code that a computer can understand. Good programmers write code that humans can understand
  • Martin Fowler, 2008.

4

5 of 17

5

6 of 17

1. Merge Sort

Base Case

6

Divide

Conquer

7 of 17

1. Merge Sort

def merge_sort (lst):

length = len(lst)

if length == 1:

return lst

else:

half1 = lst[:length//2]

half2 = lst[length//2:]

return (merge (merge_sort(half1),\

merge_sort(half2)))

8 of 17

1. Merge Function

def merge(lst1, lst2):

i, j = 0, 0

result = []

while i < len(lst1) and j < len(lst2):

next = lst1[i] if lst1[i] < \

lst2[j] else lst2[j]

result.append(next)

(i,j) = (i + 1, j) if lst1[i] < \

lst2[j] else (i, j + 1)

result.extend(lst1[i:])

result.extend(lst2[j:])

return result

9 of 17

9

10 of 17

2. Ternary Operator

next = lst1[i] \

if lst1[i] < lst2[j] \

else lst2[j]

if lst1[i] < lst2[j]:

next = lst1[i]

else:

next = lst2[j]

10

11 of 17

2. Ternary Operator

valu1 if condition else value2

  • var = x if x < y else y
  • var = "even" if x % 2 == 0 \

else "odd"

11

12 of 17

12

13 of 17

3. Tuples

  • See Slides
  • Tuples are more memory efficient than the lists. When it comes to the time efficiency, again tuples have a slight advantage over the lists especially when lookup to a value is considered. If you have data which is not meant to be changed in the first place, you should choose tuple data type over lists
  • https://www.programiz.com/python-programming/list-vs-tuples

14 of 17

3. Tuples

  • lst = [3,4]
  • tup = (3,4)
  • lst.__sizeof__() # 56 tup.__sizeof__() # 40

15 of 17

15

16 of 17

4. Lists

  • lst = [1, 2] * 3
  • lst = [1, 2] + [3, 4]
  • lst += [5, 6]
  • lst.extend ([7, 8])
  • lst.append (9)
  • lst.insert (0, -100)
  • lst.insert (-1, 300)
  • dir (lst)

17 of 17

4. List Functions

  • lst.pop (index)
  • lst.remove (item)
  • lst2 = lst.copy()
  • lst.sort()
  • lst.reverse()
  • lst.clear()