cs 330 artificial intelligence
play

CS 330 - Artificial Intelligence - Wrap up Python Programming - PowerPoint PPT Presentation

1 CS 330 - Artificial Intelligence - Wrap up Python Programming Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Fall 2019 Overview Quiz 1 next Tuesday(20 mins, closed book, closed notes) Home work


  1. 1 CS 330 - Artificial Intelligence - Wrap up Python Programming Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Fall 2019

  2. Overview • Quiz 1 next Tuesday(20 mins, closed book, closed notes) • Home work should be submitted on submission system. • Questions? 2

  3. Review • In Python3, what is 10/4 and 10//4? • In Python3, what is 2**3? • In Python3, explain a,b = b,a? • Difference of list and tuple? 3

  4. Python introduction • syntax, variable assignment, numbers • functions and getting help • booleans and conditionals • lists and objects • loops and list comprehensions and dictionaries • strings • files and trees 4

  5. Strings and dictionaries Strings One place where the Python language really shines is in the manipulation of strings. Strings syntax Either single or double quotations x = 'Pluto is a planet' y = "Pluto is a planet" True x == y Double quotes are convenient if your string contains a single quote character: print("Pluto's a planet!") print('My dog is named "Pluto"') 5

  6. Strings and dictionaries Guess: 'Pluto's a planet!' 'Pluto\'s a planet!' 6

  7. Strings and dictionaries Triple quote In addition, Python's triple quote syntax for strings lets us include newlines literally (i.e. by just hitting 'Enter' on our keyboard, rather than using the special '\n' sequence). We've already seen this in the docstrings we use to document our functions, but we can use them anywhere we want to define a string. triplequoted_hello = """hello hello world""" world print(triplequoted_hello) 7

  8. Strings and dictionaries Print without new line in Python3 The print() function automatically adds a newline character unless we specify a value for the keyword argument end other than the default value of '\n': print("hello") In python2: print("world") print("hello", end='') print "hello", print("pluto", end='') 8

  9. Strings and dictionaries String as sequences Strings can be thought of as sequences of characters. Almost everything we've seen that we can do to a list, we can also do to a string. # Indexing # Slicing # How long is this string? planet = 'Pluto' planet[-3:] len(planet) planet[0] # Yes, we can even loop over them [char+'! ' for char in planet] planet[0] = 'B' Error! Strings are immutable 9

  10. Strings and dictionaries String methods Like list, the type str has lots of very useful methods # ALL CAPS # all lowercase claim = "Pluto is a planet!" claim.lower() claim.upper() # Searching for the first index of a substring claim.index('plan') claim.startswith(planet) claim.endswith('dwarf planet') 10

  11. Strings and dictionaries str.split str.split() turns a string into a list of smaller strings, breaking on whitespace by default. This is super useful for taking you from one big string to a list of words. words = claim.split() ['Pluto', 'is', 'a', 'planet!'] words datestr = '1956-01-31' year, month, day = datestr.split('-') 11

  12. Strings and dictionaries str.join str.join() takes us in the other direction, sewing a list of strings up into one long string, using the string it was called on as a separator. '/'.join([month, day, year]) '01/31/1956' datestr = '1956-01-31' year, month, day = datestr.split('-') 12

  13. Strings and dictionaries planet + ', we miss you.' 'Pluto, we miss you.' position = 9 planet + ", you'll always be the " + position + "th planet to me.” --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-23-c7ad5a56c57a> in <module>() 1 position = 9 ----> 2 planet + ", you'll always be the " + position + "th planet to me." TypeError: must be str, not int 13

  14. Strings and dictionaries Be careful: If we want to throw in any non-string objects, we have to be careful to call str() on them first planet + ", you'll always be the " + str(position) + "th planet to me." Better way: Use format "{}, you'll always be the {}th planet to me.".format(planet, position) 14

  15. Strings and dictionaries pluto_mass = 1.303 * 10**22 earth_mass = 5.9722 * 10**24 population = 52910390 # 2 decimal points 3 decimal points, format as percent separate with commas "{} weighs about {:.2} kilograms ({:.3%} of Earth's mass). It is home to {:,} Plutonians.".format( planet, pluto_mass, pluto_mass / earth_mass, population, ) "Pluto weighs about 1.3e+22 kilograms (0.218% of Earth's mass). It is home to 52,910,390 Plutonians." 15

  16. Strings and dictionaries # Referring to format() arguments by index, starting from 0 s = """Pluto's a {0}. No, it's a {1}. {0}! {1}!""".format('planet', 'dwarf planet') print(s) 16

  17. Exercise • CS330_ex6.py

  18. Break

  19. Python introduction • syntax, variable assignment, numbers • functions and getting help • booleans and conditionals • lists and objects • loops and list comprehensions • strings and dictionaries • files and trees 19

  20. File and trees • You don’t need to import a library in order to read and write files in Python. • The first thing you’ll need to do is use Python’s built-in open function to get a file object. file_object = open(“filename”, “mode”) #where file_object is the variable to add the file object. 20

  21. File and trees • Open file mode: Including a mode argument is optional because a default value of ‘r’ will be assumed if it is omitted. The ‘r’ value stands for read mode, which is just one of many. The modes are: ‘r’ – Read mode which is used when the file is only being read ‘w’ – Write mode which is used to edit and write new information to the file (any existing files with the same name will be erased when this mode is activated) ‘a’ – Appending mode, which is used to add new data to the end of the file; that is new information is automatically amended to the end ‘r+’ – Special read and write mode, which is used to handle both actions when working with a file So, let’s take a look at a quick example. 21

  22. File and trees • Create a text file file = open(“testfile.txt”,”w”) file.write(“Hello World”) file.write(“This is our new text file”) file.write(“and this is another line.”) file.write(“Why? Because we can.”) file.close() $ cat testfile.txt 22

  23. File and trees • Read a text file file = open(“testfile.text”, “r”) print file.read() file = open(“testfile.txt”, “r”) print file.read(5) file = open(“testfile.txt”, “r”) print file.readline() file = open(“testfile.txt”, “r”) print file.readline(3) file = open(“testfile.txt”, “r”) print file.readlines() 23

  24. File and trees • Read a text file file = open(“testfile.txt”, “r”) for line in file: print line, with open(“testfile.txt”) as file: data = file.read() do something with data with open(“hello.text”, “r”) as f: data = f.readlines() for line in data: words = line.split() print words 24

  25. Tree

  26. Tree example class Tree: def __init__(self, cargo, left=None, right=None): self.cargo = cargo self.left = left self.right = right def __str__(self): return str(self.cargo)

  27. Download TreeExample.py • Learn and run it

  28. Pickle • import pickle • output = open('data.pkl', ‘wb') • # Pickle data • pickle.dump(data, output) • output.close() • # read from Pickle • pkl_file = open('data.pkl', ‘rb') • data = pickle.load(pkl_file)

  29. Sys.argv • More flexible for your program. • It could get user’s input from command • Example: • import sys • print(sys.argv)

  30. kaggle competition https://www.kaggle.com/competitions • Example1: https://www.kaggle.com/c/ understanding_cloud_organization/overview/timeline • Example2: https://www.kaggle.com/c/titanic • Example3: https://www.kaggle.com/c/zillow-prize-1 Search more dataset at: https://toolbox.google.com/datasetsearch

  31. Discussion: What features you like for Python? What is overall you experience on Python Programming? What is your interested topics?

  32. Practice reading file • Follow instructions from slides and practice in pairs. Submit exercise 6 on submission system (due on Sep. 24th). • Practice at home, and do the survey: https:// cs.plu.edu/~caora/Survey//index.php/Search/ ByID?ID=S_4_5d82a7e982dd1 • Quiz 1 and Lab 1 on next Tuesday, invited guest lecture possibly on next Thursday.

Recommend


More recommend