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

cs 330 artificial intelligence
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

CS 330 - Artificial Intelligence

  • Wrap up Python Programming

Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Fall 2019 1

slide-2
SLIDE 2

Overview

  • Quiz 1 next Tuesday(20 mins, closed book,

closed notes)

2

  • Home work should be submitted on submission

system.

  • Questions?
slide-3
SLIDE 3

Review

  • In Python3, what is 10/4 and 10//4?

3

  • In Python3, what is 2**3?
  • In Python3, explain a,b = b,a?
  • Difference of list and tuple?
slide-4
SLIDE 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

slide-5
SLIDE 5

Strings and dictionaries

Strings

One place where the Python language really shines is in the manipulation of strings.

5

Strings syntax

Either single or double quotations

x = 'Pluto is a planet' y = "Pluto is a planet" x == y True Double quotes are convenient if your string contains a single quote character: print("Pluto's a planet!") print('My dog is named "Pluto"')

slide-6
SLIDE 6

Strings and dictionaries

Guess: 'Pluto's a planet!'

6

'Pluto\'s a planet!'

slide-7
SLIDE 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.

7

triplequoted_hello = """hello world""" print(triplequoted_hello) hello world

slide-8
SLIDE 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':

8

print("hello") print("world") print("hello", end='') print("pluto", end='')

In python2: print "hello",

slide-9
SLIDE 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.

9

# Indexing planet = 'Pluto' planet[0] # Slicing planet[-3:] # How long is this string? len(planet) # Yes, we can even loop over them [char+'! ' for char in planet] planet[0] = 'B' Error! Strings are immutable

slide-10
SLIDE 10

Strings and dictionaries

String methods

Like list, the type str has lots of very useful methods

10

# ALL CAPS claim = "Pluto is a planet!" claim.upper() # all lowercase claim.lower() # Searching for the first index of a substring claim.index('plan') claim.startswith(planet) claim.endswith('dwarf planet')

slide-11
SLIDE 11

Strings and dictionaries

str.split

str.split() turns a string into a list of smaller strings, breaking

  • n whitespace by default. This is super useful for taking you

from one big string to a list of words.

11

words = claim.split() words ['Pluto', 'is', 'a', 'planet!'] datestr = '1956-01-31' year, month, day = datestr.split('-')

slide-12
SLIDE 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.

12

'/'.join([month, day, year]) '01/31/1956' datestr = '1956-01-31' year, month, day = datestr.split('-')

slide-13
SLIDE 13

Strings and dictionaries

13

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

slide-14
SLIDE 14

Strings and dictionaries

14

planet + ", you'll always be the " + str(position) + "th planet to me."

Be careful:

If we want to throw in any non-string objects, we have to be careful to call str() on them first

Better way:

Use format

"{}, you'll always be the {}th planet to me.".format(planet, position)

slide-15
SLIDE 15

Strings and dictionaries

15

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."

slide-16
SLIDE 16

Strings and dictionaries

16

# 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)

slide-17
SLIDE 17

Exercise

  • CS330_ex6.py
slide-18
SLIDE 18

Break

slide-19
SLIDE 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

slide-20
SLIDE 20

File and trees

  • You don’t need to import a library in order to read and

write files in Python.

20

  • The first thing you’ll need to do is use Python’s built-in
  • pen function to get a file object.

file_object = open(“filename”, “mode”) #where file_object is the variable to add the file object.

slide-21
SLIDE 21

File and trees

21

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

  • f 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.

  • Open file mode:
slide-22
SLIDE 22

File and trees

  • Create a text file

22

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

slide-23
SLIDE 23

File and trees

  • Read a text file

23

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

slide-24
SLIDE 24

File and trees

  • Read a text file

24

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

slide-25
SLIDE 25

Tree

slide-26
SLIDE 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)

slide-27
SLIDE 27

Download TreeExample.py

  • Learn and run it
slide-28
SLIDE 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)
slide-29
SLIDE 29

Sys.argv

  • More flexible for your program.
  • It could get user’s input from command
  • Example:
  • import sys
  • print(sys.argv)
slide-30
SLIDE 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

slide-31
SLIDE 31

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

slide-32
SLIDE 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.