TOPIC 9ISN'T IN THIS Max Fowler (Computer Science) - - PowerPoint PPT Presentation

topic 9 isn t in this
SMART_READER_LITE
LIVE PREVIEW

TOPIC 9ISN'T IN THIS Max Fowler (Computer Science) - - PowerPoint PPT Presentation

CS 105: TOPIC 8 STRINGS AND FILES TOPIC 9ISN'T IN THIS Max Fowler (Computer Science) https://pages.github-dev.cs.illinois.edu/cs-105/web/ JULY 5, 2020 Week 5 Video Series Topics String operations Slicing Splitting, joining


slide-1
SLIDE 1

CS 105: TOPIC 8 – STRINGS AND FILES TOPIC 9…ISN'T IN THIS

Max Fowler (Computer Science) https://pages.github-dev.cs.illinois.edu/cs-105/web/

JULY 5, 2020

slide-2
SLIDE 2

Week 5 Video Series Topics

String operations

Slicing Splitting, joining

Files

Writing, flushing, closing

Comma-separated values (CSV files)

Reading, splitting, filter

Coding patterns – how to recognize and apply common

idioms

slide-3
SLIDE 3

String ops – slicing

slide-4
SLIDE 4

String slicing

Slicing is how we "slice" out a part of a collection

as a copy

Given…

slide-5
SLIDE 5

Slicing my_str = "CS105"

1.

print("_{}_".format(my_str[:3]))

2.

print("_{}_".format(my_str[2:])

3.

print("_{}_".format(my_str[1:4]))

1.

_CS _

Note the white space!

2.

_ 105_

3.

_S 1_

slide-6
SLIDE 6

What about a whole slice?

my_str = "Hello" my_str_2 = my_str[:] Copies the string More important for lists later on…

slide-7
SLIDE 7

What about negative slices for "CS 105"?

print("_{}_".format(my_str[-4:-1])) Prints: _ 10_ How? -4 -> 4 spots back from the end of the string -1 -> 1 spot back from the end of the string

slide-8
SLIDE 8

Slicing out specific regions

 Remove parenthesized regions from a string

def remove_parentheticals(string): while '(' in string:

  • pen_index = string.find('(')

close_index = string.find(')') string = string[:open_index] + string[close_index + 2:] return string

slide-9
SLIDE 9

Video question

 What is the slice provided when I use the following

code? a_str = "This is an uninspired sample string." print(a_str[a.find('a'):]

slide-10
SLIDE 10

String ops – Split and Join

slide-11
SLIDE 11

What is split?

 split separates a string into a list, based on a separator.  "I want all the words in this sentence".split()  #The default is whitespace, so we'd get  ["I", "want", "all", "the", "words", "in", "this", "sentence"]  A very common separator is the comma – comma separated

variables!

 "1,2,3,4".split(",")

slide-12
SLIDE 12

Joining

Joining is the opposite of splitting! Fairly common pattern – split, process, rejoin

mylist = input.split(separator) do some processing

  • utput = separator.join(mylist)
slide-13
SLIDE 13

For example…

Given a string of comma separated

numbers…

Add two to each number and return a comma

separated string!

How can we do this?

A split, a loop, and a join!

slide-14
SLIDE 14

Video question

What list do I get when I use the following

split?

"This is a sample!".split("s")

slide-15
SLIDE 15

Files

slide-16
SLIDE 16

Files

Files are how data is stored

  • n external storage/the

"disk"

Operating system manages

the files

Disk is slow open moves files to memory in

a temporary buffer (temp storage)

slide-17
SLIDE 17

File operation - writing

file_object = open('filename', 'w') file_object.write('thing to write') file_object.close() automatic at program end file_object.flush()

  • ptional
slide-18
SLIDE 18

Or, use a with block

 Will automatically close the file at the end!

with open('filename', 'w') as outf: write stuff to outf #File is closed at this scope

  • ther code…
slide-19
SLIDE 19

Sample program -

Write a shopping list to a file…

slide-20
SLIDE 20

Video question

Opening a file moves the file temporarily

from where to where?

slide-21
SLIDE 21

CSV Files and File Reading

slide-22
SLIDE 22

Comma-separated value (CSV) files

 Very common data format  Can be generated from spreadsheet programs – or

Python!

 To process…

Each "row" is a line in the file split(',') can separate columns Indexing reads columns of interest

slide-23
SLIDE 23

Opening in general

file_object = open('filename') lines = file_object.readlines() for line in lines:

do things

slide-24
SLIDE 24

Let's take a sample CSV

I have a CSV of names and car makes/brands I want to count how many times each brand shows up!

slide-25
SLIDE 25

Video Question

 Which of these will skip the first line in a file after reading the lines in?

for line in lines[1:]: for line in lines[:1]: for line in lines[1]: for line in lines[2:]:

slide-26
SLIDE 26

Common Coding Patterns

slide-27
SLIDE 27

Coding…

Coding is a lot like building a birdhouse Recognize task -> use a pattern from your toolkit

Use a hammer and nails to fix the roof to a

birdhouse…

Use a for loop to process a list…

slide-28
SLIDE 28

Common Idioms

Check if even/odd Visit everything in a collection Sum Counter Finding "best" in collection Filtering a collection

slide-29
SLIDE 29

Check if something is even/odd

(value % 2) == 0 # returns True if value is even (value % 2) != 0 # returns True if value is odd (value % 2) == 1 # returns True if value is odd

slide-30
SLIDE 30

Visit everything in a collection

for thing in collection: … thing …

slide-31
SLIDE 31

Computing a sum / total

total = 0 # initialize variable to zero … # usually in a loop total += value # accumulate … total … # do something with the total Also Average = sum / count

slide-32
SLIDE 32

Counting

counter = 0 # initialize variable to zero … # usually in a loop and/or conditional counter += 1 # increment … counter … # do something with the counter

slide-33
SLIDE 33

Finding best in a collection

current_best = a value you know is worse than best for thing in collection: if thing is better than current_best: current_best = thing return / do something with current_best

slide-34
SLIDE 34

Filtering a collection (pattern)

newlist = [] for thing in collection: if thing meets criteria: newlist.append(thing)

slide-35
SLIDE 35

Compose patterns to solve problems

Write a function that counts the number of even

elements in a list…

What patterns are needed here?

Even/odd check pattern Filtering pattern

slide-36
SLIDE 36

Video question

You are asked to count how many strings in a list have

the longest length in the list – for example…

["zebra", "bob", "cobra", "fish", "a"] would have a

count of 2 – zebra and cobra are the longest strings

What two patterns could you combine for this task?