Nested List Comprehension and Binary Search

12
Nested List Comprehension Binary Search Python Programming for Non-Programer Department of Computer Science, NCCU {{}}

Transcript of Nested List Comprehension and Binary Search

Nested List ComprehensionBinary SearchPython Programming for Non-ProgramerDepartment of Computer Science, NCCU

{{}}

{{}}List Comprehension

Binary search

Outlines

Review list comprehension

Advance to nested list comprehension

The concept of binary search

Implementation of binary search

Q & A (about today or assignment 5)

{{}}List Comprehension

Binary search

Review List Comprehension[expression for name in list if filter]

>>> li = [1,2,3,4,5,6,7,8,9,10]>>> [x**2 for x in li if x%2==0]

[4, 16, 36, 64, 100]

{{}}List Comprehension

Binary search

Nested List ComprehensionWhat is nest? list in list, for in for

for x in list1: for y in list2: #doing sth

[[1], [1,3], [1,3,5], [1,3,5,7]]

{{}}List Comprehension

Binary search

Case 1: List in List

[[2*x - 1 for x in range(1,y+1)] for y in [1,2,3,4]]

[[1], [1,3], [1,3,5], [1,3,5,7]]

{{}}List Comprehension

Binary search

Nested List ComprehensionWhat is nest? list in list, for in for

for x in list1: for y in list2: #doing sth

[[1], [1,3], [1,3,5], [1,3,5,7]]

{{}}List Comprehension

Binary search

Case 2: For in Forfor x in list1: for y in list2: #doing sth

>>> list1=['a','b','c','d']>>> list2=['1','2','3','4']>>> [x+y for x in list1 for y in list2]['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4', 'd1', 'd2', 'd3', 'd4']

{{}}List Comprehension

Binary search

Binary Search

More effective than Linear search

For sorted sequence only

{{}}List Comprehension

Binary search

Demo!

Show in TA session

Source code: http://pastie.org/1409772

{{}}List Comprehension

Binary search

It’s your turn

Follow the Pseudo-code to build your own program.

Ask TA when you encouted a problem.

Good luck for final exam!

{{}}List Comprehension

Binary search

Pseudo-Codefunction binarySearch(Sequence, Target): low <- the beginning index of Sequence high <- the ending index of Sequence WHILE low less than high: mid <- the middle index of Sequence IF the middle value of Seqeunce larger then Target: high <- the middle of Sequence ELSE IF the middle value of Sequence less than Target: low <- the middle of Sequence ELSE: RETURN mid ENDIF ENDWHILE RETURN False

The End