What are the main data str u ct u res in P y thon ? P R AC TIC IN G - - PowerPoint PPT Presentation

what are the main data str u ct u res in p y thon
SMART_READER_LITE
LIVE PREVIEW

What are the main data str u ct u res in P y thon ? P R AC TIC IN G - - PowerPoint PPT Presentation

What are the main data str u ct u res in P y thon ? 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 Data Str u ct u re Data Str u ct u re - a speciali z ed format to organi z e


slide-1
SLIDE 1

What are the main data structures in Python?

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

Data Structure

Data Structure - a specialized format to organize and store data. Main Data Structures in Python: list tuple set dictionary

slide-3
SLIDE 3

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List

list - an ordered mutable sequence of items (e.g. numbers, strings etc.)

my_list = [1, 2, 3, 4, 5] print(my_list) [1, 2, 3, 4, 5]

slide-4
SLIDE 4

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List: accessing items

my_list = [1, 2, 3, 4, 5] print(my_list[2]) 3 print(my_list[-1]) 5 print(my_list[1:4]) [2, 3, 4] print(my_list[2:]) [3, 4, 5]

slide-5
SLIDE 5

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List: modifying items

my_list = [1, 2, 3, 4, 5] my_list[2] = 30 print(my_list) [1, 2, 30, 4, 5] my_list[:2] = [10, 20] print(my_list) [10, 20, 30, 4, 5]

slide-6
SLIDE 6

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List: methods

my_list = [10, 20, 30, 40, 50] my_list.append(60) print(my_list) [10, 20, 30, 40, 50, 60] my_list.remove(60) print(my_list) [10, 20, 30, 40, 50]

slide-7
SLIDE 7

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

List: methods

my_list = [10, 20, 30, 40, 50] my_list.pop() 50 print(my_list) [10, 20, 30, 40] my_list.count(40) 1

slide-8
SLIDE 8

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Tuple

tuple - an ordered immutable sequence of items (e.g. numbers, strings etc.)

my_tuple = (1, 'apple', 2, 'banana') print(my_tuple) (1, 'apple', 2, 'banana') my_tuple = 1, 'apple', 2, 'banana' print(my_tuple) (1, 'apple', 2, 'banana')

slide-9
SLIDE 9

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Tuple: modifying values

Modifying items in a tuple is not possible.

my_tuple[0] = 10 TypeError

slide-10
SLIDE 10

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Set

set - an unordered collection with no duplicate items (e.g. numbers, strings etc.)

my_set = set([1, 2, 3, 4, 5]) print(my_set) {1, 2, 3, 4, 5} my_set = set([1, 1, 1, 2, 3, 4, 5, 5, 5]) print(my_set) {1, 2, 3, 4, 5}

slide-11
SLIDE 11

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Set: methods

my_set1 = set([1, 2, 3, 4, 5]) my_set2 = set([3, 4, 5, 6, 7]) my_set1.add(6) print(my_set1) {1, 2, 3, 4, 5, 6} my_set1.remove(6) print(my_set1) {1, 2, 3, 4, 5} my_set1.union(my_set2) {1, 2, 3, 4, 5, 6, 7} my_set1.intersection(my_set2) {3, 4, 5} my_set1.difference(my_set2) {1, 2}

slide-12
SLIDE 12

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Dictionary

dictionary - a collection of key-value pairs where keys are unique and immutable

key → value

fruits = {'apple': 10, 'orange': 6, 'banana': 9} print(fruits) {'apple': 10, 'banana': 9, 'orange': 6} fruits = dict([('apple', 1), ('orange', 6), ('banana', 9)]) print(fruits) {'apple': 10, 'banana': 9, 'orange': 6}

slide-13
SLIDE 13

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Dictionary: accessing values

Accessing a value for a key:

fruits = {'apple': 10, 'orange': 6, 'banana': 9} fruits['apple'] 10 fruits['grapefruit'] KeyError: 'grapefruit'

slide-14
SLIDE 14

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Dictionary: modifying values

fruits['apple'] = 20 print(fruits) {'apple': 20, 'orange': 6, 'banana': 9} fruits['grapefruit'] = 11 print(fruits) {'apple': 20, 'orange': 6, 'banana': 9, 'grapefruit': 11}

slide-15
SLIDE 15

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Dictionary: methods

fruits = {'apple': 10, 'orange': 6, 'banana': 9} fruits.items() dict_items([('apple', 10), ('orange', 6), ('banana', 9)])

slide-16
SLIDE 16

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Dictionary: methods

fruits = {'apple': 10, 'orange': 6, 'banana': 9} list(fruits.items())) [('apple', 10), ('orange', 6), ('banana', 9)]

slide-17
SLIDE 17

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Dictionary: methods

fruits = {'apple': 10, 'orange': 6, 'banana': 9} fruits.keys() dict_keys(['apple', 'orange', 'banana']) fruits.values() dict_values([10, 6, 9])

slide-18
SLIDE 18

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Dictionary: methods

fruits = {'apple': 10, 'orange': 6, 'banana': 9} list(fruits.keys()) ['apple', 'orange', 'banana'] list(fruits.values()) [10, 6, 9]

slide-19
SLIDE 19

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Dictionary: methods

fruits = {'apple': 10, 'orange': 6, 'banana': 9} fruits.popitem('banana') 9 print(fruits) {'apple': 10, 'orange': 6}

slide-20
SLIDE 20

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Operations on Lists, Tuples, Sets, and Dictionaries

my_list = [1, 2, 3, 4, 5] len(my_list) 5 my_tuple = (1, 2, 3, 4, 5) len(my_tuple) 5 my_set = set([1, 2, 3, 4]) len(my_set) 4 my_dict = {'a': 1, 'b': 2, 'c': 3} len(my_dict) 3

slide-21
SLIDE 21

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Operations on Lists, Tuples, Sets, and Dictionaries

my_list = [1, 2, 3, 4, 5] 2 in my_list True my_tuple = (1, 2, 3, 4, 5) 2 in my_tuple True my_set = set([1, 2, 3, 4]) 5 in my_set False my_dict = {'a': 1, 'b': 2, 'c': 3} 'b' in my_dict True

slide-22
SLIDE 22

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-23
SLIDE 23

What are common ways to manipulate strings?

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-24
SLIDE 24

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

String

Create strings:

s = 'hello' print(s) hello s = "hello" print(s) hello

slide-25
SLIDE 25

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

String

str() constructor: str("hello") 'hello' str(11.5) '11.5' str([1, 2, 3]) '[1, 2, 3]'

slide-26
SLIDE 26

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

str() contructor

class NewClass: def __init__(self, num): self.num = num nc = NewClass(2) print(nc.num) 2 str(nc) '<__main__.NewClass instance at 0x105cdabd8>'

slide-27
SLIDE 27

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

str() constructor

class NewClass: def __init__(self, num): self.num = num def __str__(self): return str(self.num) nc = NewClass(3) str(nc) '3'

slide-28
SLIDE 28

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Accessing characters in a string

s = "interview" s[1] 'n' s[-2] 'e' s[1:4] 'nte' s[2:] 'terview' s[:3] 'int'

slide-29
SLIDE 29

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

The .index() method

s = "interview" s.index('n') 1 s.index('i')

slide-30
SLIDE 30

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Strings are immutable

s[0] = 'a' TypeError .capitalize() .lower() .upper() .replace()

Methods return a new string object

slide-31
SLIDE 31

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Modifying methods 1

# String concatencation s1 = "worm" s2 = s1 + "hole" print(s2) wormhole # Replace a substring s1 = 'a dog ate my food' s2 = s1.replace('dog', 'cat') print(s2) a cat ate my food

slide-32
SLIDE 32

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Modifying methods 2

# Upper case s3 = s2.upper() print(s3) A CAT ATE MY FOOD # Lower case s4 = s3.lower() print(s4) a cat ate my food # Capitalization s5 = s4.capitalize() print(s5) A cat ate my food

slide-33
SLIDE 33

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Relation to lists

Create a string from a list of strings:

l = ['I', 'like', 'to', 'study'] s = ' '.join(l) print(s) I like to study

Breaking a string into a list of strings:

l = s.split(' ') print(l) ['I', 'like', 'to', 'study']

slide-34
SLIDE 34

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

String methods with DataFrames

import pandas as pd d = {'name': ['john', 'amanda', 'rick'], 'age': [35, 29, 19]} D = pd.DataFrame(d) print(D) name age 0 john 35 1 amanda 29 2 rick 19

slide-35
SLIDE 35

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

String methods with DataFrames

D['name'] = # we will modify this column

slide-36
SLIDE 36

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

String methods with DataFrames

D['name'] = D['name']

slide-37
SLIDE 37

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

String methods with DataFrames

D['name'] = D['name'].str

slide-38
SLIDE 38

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

String methods with DataFrames

D['name'] = D['name'].str.capitalize() print(D) name age 0 John 35 1 Amanda 29 2 Rick 19

slide-39
SLIDE 39

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-40
SLIDE 40

How to write regular expressions in Python?

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-41
SLIDE 41

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Definition

Regular expression - a sequence of special characters (metacharacters) dening a paern to search in a text. cat "I have a cat. My cat likes to eat a lot. It also catches mice."

slide-42
SLIDE 42

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Definition

Regular expression - a sequence of special characters (metacharacters) dening a paern to search in a text. cat "I have a cat. My cat likes to eat a lot. It also catches mice."

slide-43
SLIDE 43

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Complex patterns

Example: john.smith@mailbox.com is the e-mail of John. He oen writes to his boss at boss@big- company.com. But the messages get forwarded to his secretary at info@big-company.com.

slide-44
SLIDE 44

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Complex patterns

Example: **john.smith@mailbox.com is the e-mail of John. He oen writes to his boss at boss@big- company.com. But the messages get forwarded to his secretary at info@big- company.com**.

slide-45
SLIDE 45

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Special characters

Simple characters and numbers are mapped onto themselves:

a → a A → A 1 → 1

Dot maps to anything:

. → any character . → 'a' , '1' , '"' , ' ' , ... \. → .

slide-46
SLIDE 46

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Special characters

The following metacharacters represent \ followed by a leer:

\w → any alphanumeric character or underscore \w → '1' , 'a' , '_' , ... \d → any digit \d → '1' , '2' , '3' , ... \s → any whitespace character \s → ' ' , '\t' , ...

slide-47
SLIDE 47

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Square brackets

Several metacharacters can be enclosed in square brackets:

[aAbB] → a , A , b , B [a-z] → a , b , c , ... [A-Z] → A , B , C , ... [0-9] → 0 , 1 , 2 , ... [A-Za-z] → A , B , C , ..., a , b , c , ...

slide-48
SLIDE 48

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Repetitions

* → no character or it repeats an undened number of times a* → '' , 'a' , 'aa' , ... + → the character is present at least once a+ → 'a' , 'aa' , 'aaa' , ... ? → the character exists or not a? → '' , 'a' {n, m} → the character is present from n to m times a{2, 4} → 'aa' , 'aaa' , 'aaaa'

slide-49
SLIDE 49

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Regular expression for an e-mail

Example: **john.smith@mailbox.com is the e-mail of John. He oen writes to his boss at boss@company.com. But the messages get forwarded to his secretary at info@company.com**.

[\w\.]+@[a-z]+\.[a-z]+

slide-50
SLIDE 50

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Regular expression for an e-mail

Example: **john.smith@mailbox.com is the e-mail of John. He oen writes to his boss at boss@company.com. But the messages get forwarded to his secretary at info@company.com**.

[\w\.]+ @[a-z]+\.[a-z]+ [\w\.]+ → john.smith , boss , info

at least one leer, digit, underscore, or dot character

slide-51
SLIDE 51

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Regular expression for an e-mail

Example: **john.smith@mailbox.com is the e-mail of John. He oen writes to his boss at boss@company.com. But the messages get forwarded to his secretary at info@company.com**.

[\w\.]+ @ [a-z]+\.[a-z]+

@ → @

slide-52
SLIDE 52

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Regular expression for an e-mail

Example: **john.smith@mailbox.com is the e-mail of John. He oen writes to his boss at boss@company.com. But the messages get forwarded to his secretary at info@company.com**.

[\w\.]+@ [a-z]+ \.[a-z]+ [a-z]+ → mailbox , company

at least one lowercased leer

slide-53
SLIDE 53

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Regular expression for an e-mail

Example: **john.smith@mailbox.com is the e-mail of John. He oen writes to his boss at boss@company.com. But the messages get forwarded to his secretary at info@company.com**.

[\w\.]+@[a-z]+ \. [a-z]+ \. → .

slide-54
SLIDE 54

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

Regular expression for an e-mail

Example: **john.smith@mailbox.com is the e-mail of John. He oen writes to his boss at boss@company.com. But the messages get forwarded to his secretary at info@company.com**.

[\w\.]+@[a-z]+\. [a-z]+ [a-z]+ → com

at least one lowercased leer

slide-55
SLIDE 55

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

re package

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.com.'

slide-56
SLIDE 56

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

re.finditer()

result = re.finditer(pattern, text) print(result) <callable_iterator object at 0x7f5dff81af98> for match in result: print(match) <_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-57
SLIDE 57

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

re.finditer()

result = re.finditer(pattern, text) print(result) <callable_iterator object ...> for match in result: print(match.group()) print(match.start()) print(match.end()) john.smith@mailbox.com 22 boss@company.com 77 93 info@company.com 146 162

slide-58
SLIDE 58

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

re.findall()

substrings = re.findall(pattern, text) print(substrings) ['john.smith@mailbox.com', 'boss@company.com', 'info@company.com']

slide-59
SLIDE 59

PRACTICING CODING INTERVIEW QUESTIONS IN PYTHON

re.split()

split_list = re.split(pattern, text) print(split_list) ['', ' is the e-mail of John. He often writes to his boss at ', '. But the messages get forwarded to his secretary at ', '.']

slide-60
SLIDE 60

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