topic 9 isn t in this
play

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


  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

  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

  3. String ops – slicing

  4. String slicing  Slicing is how we "slice" out a part of a collection as a copy  Given…

  5. Slicing my_str = "CS105" print("_{}_".format(my_str[:3])) _CS _ 1. 1.  Note the white space! print("_{}_".format(my_str[2:]) 2. _ 105_ 2. print("_{}_".format(my_str[1:4])) 3. _S 1_ 3.

  6. What about a whole slice?  my_str = "Hello"  my_str_2 = my_str[:]  Copies the string  More important for lists later on…

  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

  8. Slicing out specific regions  Remove parenthesized regions from a string def remove_parentheticals(string): while '(' in string: open_index = string.find('(') close_index = string.find(')') string = string[:open_index] + string[close_index + 2:] return string

  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'):]

  10. String ops – Split and Join

  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(",")

  12. Joining  Joining is the opposite of splitting!  Fairly common pattern – split, process, rejoin mylist = input.split(separator) do some processing output = separator.join(mylist)

  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!

  14. Video question  What list do I get when I use the following split?  "This is a sample!".split("s")

  15. Files

  16. Files  Files are how data is stored on external storage/the "disk"  Operating system manages the files  Disk is slow  open moves files to memory in a temporary buffer (temp storage)

  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() optional

  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 other code…

  19. Sample program -  Write a shopping list to a file…

  20. Video question  Opening a file moves the file temporarily from where to where?

  21. CSV Files and File Reading

  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

  23. Opening in general file_object = open('filename') lines = file_object.readlines() for line in lines: do things

  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!

  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:]:

  26. Common Coding Patterns

  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…

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

  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

  30. Visit everything in a collection for thing in collection : … thing …

  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

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

  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

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

  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

  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?

Recommend


More recommend