What are iterable objects ? P R AC TIC IN G C OD IN G IN TE R VIE - - PowerPoint PPT Presentation

what are iterable objects
SMART_READER_LITE
LIVE PREVIEW

What are iterable objects ? P R AC TIC IN G C OD IN G IN TE R VIE - - PowerPoint PPT Presentation

What are iterable objects ? P R AC TIC IN G C OD IN G IN TE R VIE W QU E STION S IN P YTH ON Kirill Smirno v Data Science Cons u ltant , Altran Definition iterable objects / Iterables - an y object that can be u sed in a for loop list t u ple


slide-1
SLIDE 1

What are iterable

  • bjects?

P R AC TIC IN G C OD IN G IN TE R VIE W QU E STION S IN P YTH ON

Kirill Smirnov

Data Science Consultant, Altran

slide-2
SLIDE 2

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Definition

iterable objects / Iterables - any object that can be used in a for loop list tuple set dictionary string

slide-3
SLIDE 3

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Iterating through a list or tuple

list:

droids = ['R2-D2', 'TC-16', 'C-3PO'] for droid in droids: print(droid) R2-D2 TC-16 C-3PO

tuple:

droids = ('R2-D2', 'TC-16', 'C-3PO') for droid in droids: print(droid) R2-D2 TC-16 C-3PO

slide-4
SLIDE 4

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Iterating through a set

battleships = {'X-Wing Fighter', 'Millennium Falcon', 'TIE Fighter'} for battleship in battleships: print(battleship) TIE Fighter X-Wing Fighter Millennium Falcon

slide-5
SLIDE 5

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Iterating through a string

title = 'Star Wars' for char in title: print(char) S t a r W a r s

slide-6
SLIDE 6

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Iterating through a dictionary

episodes = { 'Episode I': 'The Phantom Menace', 'Episode II': 'Attack of the Clones', 'Episode III': 'Revenge of the Sith', 'Episode IV': 'A New Hope', 'Episode V': 'The Empire Strikes Back', 'Episode VI': 'Return of the Jedi' } for episode in episodes: print(episode) Episode I Episode II Episode III Episode IV Episode V Episode VI

slide-7
SLIDE 7

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Getting key-value pairs

episodes = { 'Episode I': 'The Phantom Menace', 'Episode II': 'Attack of the Clones', 'Episode III': 'Revenge of the Sith', 'Episode IV': 'A New Hope', 'Episode V': 'The Empire Strikes Back', 'Episode VI': 'Return of the Jedi' } for item in episodes.items(): print(item) ('Episode I', 'The Phantom Menace') ('Episode II', 'Attack of the Clones') ('Episode III', 'Revenge of the Sith') ('Episode IV', 'A New Hope') ('Episode V', 'The Empire Strikes Back') ('Episode VI', 'Return of the Jedi')

slide-8
SLIDE 8

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Getting key-value pairs

episodes = { 'Episode I': 'The Phantom Menace', 'Episode II': 'Attack of the Clones', 'Episode III': 'Revenge of the Sith', 'Episode IV': 'A New Hope', 'Episode V': 'The Empire Strikes Back', 'Episode VI': 'Return of the Jedi' } for title, subtitle in episodes.items(): print(title + ': ' + subtitle) 'Episode I': 'The Phantom Menace' 'Episode II': 'Attack of the Clones' 'Episode III': 'Revenge of the Sith' 'Episode IV': 'A New Hope' 'Episode V': 'The Empire Strikes Back' 'Episode VI': 'Return of the Jedi'

slide-9
SLIDE 9

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Less visual objects: range

interval = range(0, 10) print(interval) range(0, 10) for num in interval: print(num) 1 2 ... 9

slide-10
SLIDE 10

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Less visual objects: enumerate

villains = ['Darth Maul', 'Palpatine', 'Darth Vader'] enum_villains = enumerate(villains) for item in enum_villains: print(item) (0, 'Darth Maul') (1, 'Palpatine') (2, 'Darth Vader')

slide-11
SLIDE 11

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Less visual objects: enumerate

villains = ['Darth Maul', 'Palpatine', 'Darth Vader'] enum_villains = enumerate(villains) for idx, name in enum_villains: print(str(idx) + ' - ' + name) 0 - Darth Maul 1 - Palpatine 2 - Darth Vader

slide-12
SLIDE 12

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Iterables as arguments

list() , tuple() , set() , etc.

villains = [ 'Darth Maul', 'Palpatine', 'Darth Vader' ] list(enumerate(villains)) [ (0, 'Darth Maul'), (1, 'Palpatine'), (2, 'Darth Vader') ]

slide-13
SLIDE 13

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Iterables as arguments

list() , tuple() , set() , etc.

villains = [ 'Darth Maul', 'Palpatine', 'Darth Vader' ] list(enumerate(villains)) [ (0, 'Darth Maul'), ... set(enumerate(villains)) { (0, 'Darth Maul'), (1, 'Palpatine'), (2, 'Darth Vader') }

slide-14
SLIDE 14

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

How to know if we deal with an Iterable

interval = range(0, 5) interval_iter = iter(interval) print(interval_iter) <range_iterator object at 0x7f3bdf8ad300>

Iterator - an object knowing how to retrieve consecutive elements from an Iterable one by

  • ne

next(interval_iter) next(interval_iter) 1 next(interval_iter) 2

slide-15
SLIDE 15

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

StopIteration

next(interval_iter) 3 next(interval_iter) 4 next(interval_iter) StopIteration

slide-16
SLIDE 16

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Describing a for loop

droids = ['R2-D2', 'TC-16', 'C-3PO'] for droid in droids: print(droid) R2-D2 TC-16 C-3PO iter_droids = iter(droids) while True: try: except StopIteration: break

slide-17
SLIDE 17

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Describing a for loop

droids = ['R2-D2', 'TC-16', 'C-3PO'] for droid in droids: print(droid) R2-D2 TC-16 C-3PO iter_droids = iter(droids) while True: try: droid = next(iter_droid) print(droid) except StopIteration: break R2-D2 TC-16 C-3PO

slide-18
SLIDE 18

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Many Iterables are Iterators

iter() next() e.g. enumerate, nditer etc.

import re pattern = re.compile(r'[\w\.]+@[a-z]+\.[a-z]+') text = 'john.smith@mailbox.com is the e-mail of John. He often writes to his boss '\ 'at boss@company.com. But the messages get forwarded to his secretary at info@company.co result = re.finditer(pattern, text)

slide-19
SLIDE 19

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

iter() or next()

iter()

result = re.finditer(pattern, text) for item in result: print(item) <_sre.SRE_Match object; span=(0, 22), match='john.smith@mailbox.com'> <_sre.SRE_Match object; span=(77, 93), match='boss@company.com'> <_sre.SRE_Match object; span=(146, 162), match='info@company.com'>

slide-20
SLIDE 20

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

iter() or next()

next()

result = re.finditer(pattern, text) next(result) <_sre.SRE_Match object; span=(0, 22), match='john.smith@mailbox.com'> next(result) <_sre.SRE_Match object; span=(77, 93), match='boss@company.com'> next(result) <_sre.SRE_Match object; span=(146, 162), match='info@company.com'>

slide-21
SLIDE 21

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Expendable Iterables

result = re.finditer(pattern, text) for item in result: print(item) <_sre.SRE_Match object; ... <_sre.SRE_Match object; ... <_sre.SRE_Match object; ... for item in result: print(item) # nothing short_list = [2, 4] for item in short_list: print(item) 2 4 for item in short_list: print(item) 2 4

slide-22
SLIDE 22

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Traversing a DataFrame

pars = {'weight': [168, 183, 198], 'height': [77, 79, 135]} characters = pd.DataFrame(pars, index=['Luke Skywalker', 'Han Solo', 'Darth Vader']) print(characters) weight height Luke Skywalker 168 77 Han Solo 183 79 Darth Vader 198 135

slide-23
SLIDE 23

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Direct approach

for item in characters: print(item) weight height

slide-24
SLIDE 24

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

.iterrows()

result = characters.iterrows() print(result) <generator object DataFrame.iterrows at 0x7f5dff6b9c50>

slide-25
SLIDE 25

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

.iterrows()

result = characters.iterrows() for item in result: print(item)

item → (index name, Series)

('Luke Skywalker', weight 168 height 77 Name: Luke Skywalker, dtype: int64) ('Han Solo', weight 183 height 79 Name: Han Solo, dtype: int64) ('Darth Vader', weight 198 height 135 Name: Darth Vader, dtype: int64)

slide-26
SLIDE 26

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

.iterrows()

result = characters.iterrows() for index, series in result: print(index) print(series) Luke Skywalker weight 168 height 77 Name: Luke Skywalker, dtype: int64) Han Solo weight 183 height 79 Name: Han Solo, dtype: int64) Darth Vader weight 198 height 135 Name: Darth Vader, dtype: int64)

slide-27
SLIDE 27

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

.iteritems()

result = characters.iteritems() print(result) <generator object DataFrame.iteritems at 0x7f5dff69f938>

slide-28
SLIDE 28

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

.iteritems()

result = characters.iteritems() for item in result: print(item)

item → (column name, Series)

('weight', Luke Skywalker 168 Han Solo 183 Darth Vader 198 Name: weight, dtype: int64) ('height', Luke Skywalker 77 Han Solo 79 Darth Vader 135 Name: height, dtype: int64)

slide-29
SLIDE 29

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

.iteritems()

result = characters.iteritems() for name, series in result: print(name) print(series) weight Luke Skywalker 168 Han Solo 183 Darth Vader 198 Name: weight, dtype: int64 height Luke Skywalker 77 Han Solo 79 Darth Vader 135 Name: height, dtype: int64

slide-30
SLIDE 30

Let's practice!

P R AC TIC IN G C OD IN G IN TE R VIE W QU E STION S IN P YTH ON

slide-31
SLIDE 31

What is a list comprehension?

P R AC TIC IN G C OD IN G IN TE R VIE W QU E STION S IN P YTH ON

Kirill Smirnov

Data Science Consultant, Altran

slide-32
SLIDE 32

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List comprehension

nums = [2, 4, 6, 8, 10] print(nums) [2, 4, 6, 8, 10] nums_new = [] for i in range(1, 6): nums_new.append(2*i) print(nums_new) [2, 4, 6, 8, 10]

slide-33
SLIDE 33

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List comprehension

nums = [2, 4, 6, 8, 10] print(nums) [2, 4, 6, 8, 10] for num in range(1, 6)

slide-34
SLIDE 34

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List comprehension

nums = [2, 4, 6, 8, 10] print(nums) [2, 4, 6, 8, 10] [ for num in range(1, 6)]

slide-35
SLIDE 35

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List comprehension

nums = [2, 4, 6, 8, 10] print(nums) [2, 4, 6, 8, 10] [(2 * num) for num in range(1, 6)]

slide-36
SLIDE 36

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List comprehension

nums = [2, 4, 6, 8, 10] print(nums) [2, 4, 6, 8, 10] nums_new = [(2 * num) for num in range(1, 6)] print(nums_new) [2, 4, 6, 8, 10]

slide-37
SLIDE 37

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Summing up

List comprehension is dened by:

slide-38
SLIDE 38

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Summing up

List comprehension is dened by: an iterable object (e.g. list, tuple, set)

[ for num in range(1, 6)]

slide-39
SLIDE 39

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Summing up

List comprehension is dened by: an iterable object (e.g. list, tuple, set) an operation on an element

[(2 * num) for num in range(1, 6)]

(optional) conditions

slide-40
SLIDE 40

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List comprehension with condition

nums = [2, 4, 6, 8, 10] print(nums) [2, 4, 6, 8, 10]

1 2 3 4 5 6 7 8 9 10

slide-41
SLIDE 41

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List comprehension with condition

nums = [2, 4, 6, 8, 10] print(nums) [2, 4, 6, 8, 10]

1 2 3 4 5 6 7 8 9 10 → 2 4 6 8 10

slide-42
SLIDE 42

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Adding a condition

nums_new = [num for num in range(1, 11)] print(nums_new) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

slide-43
SLIDE 43

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Adding a condition

nums_new = [num for num in range(1, 11) if num % 2 == 0] print(nums_new) [2, 4, 6, 8, 10]

slide-44
SLIDE 44

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

More examples

text = 'list COMPREHENSION is A way TO create LISTS'

Task: Create a list that contains the length of each lowercased word.

list , is , way , create → [4, 2, 3, 6]

slide-45
SLIDE 45

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

More examples

text = 'list COMPREHENSION is A way TO create LISTS'

Task: Create a list that contains the length of each lowercased word.

list , is , way , create → [4, 2, 3, 6]

  • utput = [ for word in text.split() ]
slide-46
SLIDE 46

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

More examples

text = 'list COMPREHENSION is A way TO create LISTS'

Task: Create a list that contains the length of each lowercased word.

list , is , way , create → [4, 2, 3, 6]

  • utput = [ for word in text.split() if word.islower()]
slide-47
SLIDE 47

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

More examples

text = 'list COMPREHENSION is A way TO create LISTS'

Task: Create a list that contains the length of each lowercased word.

list , is , way , create → [4, 2, 3, 6]

  • utput = [len(word) for word in text.split() if word.islower()]

print(output) [4, 2, 3, 6]

slide-48
SLIDE 48

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Multiple loops

numbers = [1, 2, 3] letters = ['a', 'b', 'c']

Create all the possible pairs between numbers and letters :

[ (1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c'), ]

slide-49
SLIDE 49

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Iterating through multiple loops

numbers = [1, 2, 3] letters = ['a', 'b', 'c'] pairs = [ for i in numbers ]

slide-50
SLIDE 50

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Iterating through multiple loops

numbers = [1, 2, 3] letters = ['a', 'b', 'c'] pairs = [ for i in numbers for j in letters]

slide-51
SLIDE 51

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Iterating through multiple loops

numbers = [1, 2, 3] letters = ['a', 'b', 'c'] pairs = [(i, j) for i in numbers for j in letters] print(pairs) [ (1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c'), ]

slide-52
SLIDE 52

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Deeper look

numbers = [1, 2, 3] letters = ['a', 'b', 'c'] pairs = [(i, j) for i in numbers for j in letters] pairs = [] for i in numbers: for j in letters: pairs.append((i, j))

slide-53
SLIDE 53

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Deeper look

numbers = [1, 2, 3] letters = ['a', 'b', 'c'] pairs = [(i, j) for j in letters] pairs = [] for j in letters: pairs.append((i, j))

slide-54
SLIDE 54

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Deeper look

numbers = [1, 2, 3] letters = ['a', 'b', 'c'] pairs = [(i, j) for i in numbers ] pairs = [] for i in numbers: pairs.append((i, j))

slide-55
SLIDE 55

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Adding square brackets

pairs = [ (i, j) for i in numbers for j in letters]

slide-56
SLIDE 56

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Adding square brackets

pairs = [[(i, j) for i in numbers] for j in letters] print(pairs) [ [(1, 'a'), (2, 'a'), (3, 'a')], [(1, 'b'), (2, 'b'), (3, 'b')], [(1, 'c'), (2, 'c'), (3, 'c')] ]

slide-57
SLIDE 57

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Adding square brackets

pairs = [[(i, j) for i in numbers] for j in letters] pairs = [] for j in letters: temp = [] for i in numbers: temp.append((i, j)) pairs.append(temp)

slide-58
SLIDE 58

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Adding square brackets

pairs = [[(i, j) for i in numbers] ] pairs = [] temp = [] for i in numbers: temp.append((i, j)) pairs.append(temp)

slide-59
SLIDE 59

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Adding square brackets

pairs = [[(i, j) ] for j in letters] pairs = [] for j in letters: temp = [] temp.append((i, j)) pairs.append(temp)

slide-60
SLIDE 60

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Swap numbers and letters

numbers = [1, 2, 3] letters = ['a', 'b', 'c'] pairs = [[(i, j) for i in numbers] for j in letters] print(pairs) [ [(1, 'a'), (2, 'a'), (3, 'a')], [(1, 'b'), (2, 'b'), (3, 'b')], [(1, 'c'), (2, 'c'), (3, 'c')] ]

slide-61
SLIDE 61

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Swap numbers and letters

numbers = [1, 2, 3] letters = ['a', 'b', 'c'] pairs = [[(i, j) for i in letters] for j in numbers] print(pairs) [ [('a', 1), ('b', 1), ('c', 3)], [('a', 2), ('b', 2), ('c', 3)], [('a', 3), ('b', 3), ('c', 3)] ]

slide-62
SLIDE 62

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Difference between list comprehensions

numbers = [1, 2, 3] letters = ['a', 'b', 'c'] pairs = [(i, j) for i in numbers for j in letters] pairs = [[(i, j) for i in numbers] for j in letters] pairs = [[(i, j) for i in letters] for j in numbers]

slide-63
SLIDE 63

Let's practice!

P R AC TIC IN G C OD IN G IN TE R VIE W QU E STION S IN P YTH ON

slide-64
SLIDE 64

What is a zip

  • bject?

P R AC TIC IN G C OD IN G IN TE R VIE W QU E STION S IN P YTH ON

Kirill Smirnov

Data Science Consultant, Altran

slide-65
SLIDE 65

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Definition

zip - object that combines several iterable objects into one iterable object.

e - an element from an Iterable

i

slide-66
SLIDE 66

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Definition

zip - object that combines several iterable objects into one iterable object.

e - an element from an Iterable

i

slide-67
SLIDE 67

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Definition

zip - object that combines several iterable objects into one iterable object.

e - an element from an Iterable

i

slide-68
SLIDE 68

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Example

title = 'TMNT' villains = ['Shredder', 'Krang', 'Bebop', 'Rocksteady'] turtles = { 'Raphael': 'Sai', 'Michelangelo': 'Nunchaku', 'Leonardo': 'Twin katana', 'Donatello': 'Bo' } result = zip(title, villains, turtles) print(result) <zip object at 0x7f37bab6e608>

slide-69
SLIDE 69

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Traversing through a zip object

result = zip(title, villains, turtles) for item in result: print(item) ('T', 'Shredder', 'Raphael') ('M', 'Krang', 'Michelangelo') ('N', 'Bebop', 'Leonardo') ('T', 'Rocksteady', 'Donatello')

slide-70
SLIDE 70

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Returning a list of tuples

result = zip(title, villains, turtles) tuples = list(result) print(tuples) [ ('T', 'Shredder', 'Raphael'), ('M', 'Krang', 'Michelangelo'), ('N', 'Bebop', 'Leonardo'), ('T', 'Rocksteady', 'Donatello') ]

slide-71
SLIDE 71

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

zip object as Iterator

result = zip(title, villains, turtles) next(result) ('T', 'Shredder', 'Raphael') next(result) ('M', 'Krang', 'Michelangelo') next(result) ('N', 'Bebop', 'Leonardo') next(result) ('T', 'Rocksteady', 'Donatello') next(result) StopIteration

slide-72
SLIDE 72

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

zip object is expendable

result = zip(title, villains, turtles) for item in result: print(item) ('T', 'Shredder', 'Raphael') ('M', 'Krang', 'Michelangelo') ('N', 'Bebop', 'Leonardo') ('T', 'Rocksteady', 'Donatello')

slide-73
SLIDE 73

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

zip object is expendable

result = zip(title, villains, turtles) for item in result: print(item) ('T', 'Shredder', 'Raphael') ('M', 'Krang', 'Michelangelo') ... for item in result: print(item) # nothing result = zip(title, villains, turtles) tuples = list(result) print(tuples) [ ('T', 'Shredder', 'Raphael'), ('M', 'Krang', 'Michelangelo'), ('N', 'Bebop', 'Leonardo'), ('T', 'Rocksteady', 'Donatello') ]

slide-74
SLIDE 74

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

'zip' object is expendable

result = zip(title, villains, turtles) for item in result: print(item) ('T', 'Shredder', 'Raphael') ('M', 'Krang', 'Michelangelo') ... for item in result: print(item) # nothing result = zip(title, villains, turtles) tuples = list(result) print(tuples) [ ('T', 'Shredder', 'Raphael'), ... tuples = list(result) print(tuples) []

slide-75
SLIDE 75

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Unequal Iterable sizes

title = 'TMNT' villains = ['Shredder', 'Krang', 'Bebop', 'Rocksteady'] turtles = { 'Raphael': 'Sai', 'Michelangelo': 'Nunchaku', 'Leonardo': 'Twin katana', 'Donatello': 'Bo' }

slide-76
SLIDE 76

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Unequal Iterable sizes

title = 'Teenage Mutant Ninja Turtles' villains = ['Shredder', 'Krang', 'Bebop', 'Rocksteady'] turtles = { 'Raphael': 'Sai', 'Michelangelo': 'Nunchaku', 'Leonardo': 'Twin katana', 'Donatello': 'Bo' } result = zip(title, villains, turtles)

slide-77
SLIDE 77

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Traversing through the 'zip' object

result = zip(title, villains, turtles) for item in result: print(item) ('T', 'Shredder', 'Raphael') ('e', 'Krang', 'Michelangelo') ('e', 'Bebop', 'Leonardo') ('n', 'Rocksteady', 'Donatello')

slide-78
SLIDE 78

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Reverse operation

turtle_masks = [ ('Raphael', 'red'), ('Michelangelo', 'orange'), ('Leonardo', 'blue'), ('Donatello', 'purple') ] result = zip(*turtle_masks) print(result) [ ('Raphael', 'Michelangelo', 'Leonardo', 'Donatello'), ('red', 'orange', 'blue', 'purple') ]

slide-79
SLIDE 79

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Unequal tuple sizes

turtle_masks = [ ('Raphael', 'red'), ('Michelangelo', 'orange'), ('Leonardo', 'blue', 'cyan'), ('Donatello', 'purple', 'magenta') ] result = zip(*turtle_masks) print(result) [ ('Raphael', 'Michelangelo', 'Leonardo', 'Donatello'), ('red', 'orange', 'blue', 'purple') ]

slide-80
SLIDE 80

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Relation to a dictionary

A zip object can be used to create a dictionary

keys = ['movie', 'year', 'director'] values = [ ['Forest Gump', 'Goodfellas', 'Se7en'], [1994, 1990, 1995], ['R.Zemeckis', 'M.Scorsese', 'D.Fincher'] ] movies = dict(zip(keys, values)) print(movies) { 'director': [ 'R.Zemeckis', 'M.Scorsese', 'D.Fincher' ], 'movie': [ 'Forest Gump', 'Goodfellas', 'Se7en' ], 'year': [1994, 1990, 1995] }

slide-81
SLIDE 81

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Creating a DataFrame

import pandas as pd df_movies = pd.DataFrame(movies) print(df_movies) director movie year 0 Robert Zemeckis Forest Gump 1994 1 Martin Scorsese Goodfellas 1990 2 David Fincher Se7en 1995

list()

slide-82
SLIDE 82

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Creating a DataFrame

import pandas as pd df_movies = pd.DataFrame(movies) print(df_movies) director movie year 0 Robert Zemeckis Forest Gump 1994 1 Martin Scorsese Goodfellas 1990 2 David Fincher Se7en 1995

list() → zip()

slide-83
SLIDE 83

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Creating a DataFrame

import pandas as pd df_movies = pd.DataFrame(movies) print(df_movies) director movie year 0 Robert Zemeckis Forest Gump 1994 1 Martin Scorsese Goodfellas 1990 2 David Fincher Se7en 1995

list() → zip() → dict()

slide-84
SLIDE 84

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Creating a DataFrame

import pandas as pd df_movies = pd.DataFrame(movies) print(df_movies) director movie year 0 Robert Zemeckis Forest Gump 1994 1 Martin Scorsese Goodfellas 1990 2 David Fincher Se7en 1995

list() → zip() → dict() → DataFrame()

slide-85
SLIDE 85

Let's practice!

P R AC TIC IN G C OD IN G IN TE R VIE W QU E STION S IN P YTH ON

slide-86
SLIDE 86

What is a generator and how to create

  • ne?

P R AC TIC IN G C OD IN G IN TE R VIE W QU E STION S IN P YTH ON

Kirill Smirnov

Data Science Consultant, Altran

slide-87
SLIDE 87

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Definition

Generator - a special iterable object created by a function having a yield keyword in its body.

def func(): # Return a value from super complex calculations return 0 result = func() print(result)

slide-88
SLIDE 88

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Definition

Generator - a special iterable object created by a function having a yield keyword in its body.

def func(): # Yield a value from super complex calculations yield 0 result = func() print(result) <generator object result at 0x105736e10>

slide-89
SLIDE 89

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Generator as Iterable

def func(): # Yield a value from super complex calculations yield 0 result = func() for item in result: print(item)

slide-90
SLIDE 90

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

More yields!

def func(): yield 0 yield 1 yield 2 result = func() for item in result: print(item) 1 2

slide-91
SLIDE 91

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Yield in a loop

def func(n): for i in range(0, n): yield 2*i result = func(3) for item in result: print(item) 2 4

slide-92
SLIDE 92

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Converting a generator to a list

def func(n): for i in range(0, n): yield 2*i result = func(5) list(result) [0, 2, 4, 6, 8]

slide-93
SLIDE 93

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Generator as Iterator

Generator is an Iterable AND an Iterator

def func(n): for i in range(0, n): yield 2*i result = func(3) next(result) next(result) 2 next(result) 4 next(result) StopIteration

slide-94
SLIDE 94

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Generators are expendable

def func(n): for i in range(0, n): yield 2*i result = func(3) for item in result: print(item) 2 4 for item in result: print(item) # nothing result = func(3) for item in result: print(item) 2 4

slide-95
SLIDE 95

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Generators are expendable

def func(n): for i in range(0, n): yield 2*i result = func(3) list(result) [0, 2, 4] list(result) [] result = func(3) list(result) [0, 2, 4]

slide-96
SLIDE 96

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Generator comprehension

result = [2*i for i in range(0, 3)] print(result) [0, 2, 4] result = (2*i for i in range(0, 3)) print(result) <generator object result at 0x105736e10>

slide-97
SLIDE 97

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Traversal

result = (2*i for i in range(0, 3)) for item in result: print(item) 1 2 next(result) StopIteration

slide-98
SLIDE 98

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Why generators?

simple way to create a custom iterable

  • bject

[1, 3, 2, 4, 3, 5]

def create_jump_sequence(n): for i in range(1, n-1): yield i yield i+2 jump_sequence = create_jump_sequence(4) list(jump_sequence) [1, 3, 2, 4, 3, 5]

slide-99
SLIDE 99

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Why generators?

simple way to create a custom iterable

  • bject

lazy initialization

[1, 3, 2, 4, 3, 5, 4, 6, 5, 7, ...]

def create_jump_sequence(n): for i in range(1, n-1): yield i yield i+2 jump_sequence = create_jump_sequence(500) next(jump_sequence) 1

slide-100
SLIDE 100

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Why generators?

simple way to create a custom iterable

  • bject

lazy initialization possibility to create innite iterable objects

def create_inf_generator(): while True: yield 'I am infinite!' inf_generator = create_inf_generator() next(inf_generator) I am infinite

slide-101
SLIDE 101

Let's practice!

P R AC TIC IN G C OD IN G IN TE R VIE W QU E STION S IN P YTH ON