Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Python Lecture Plan for Introduction to AI Course, Study notes of Voice

A lecture plan for a Python course focused on artificial intelligence. It covers topics such as list comprehensions, iterators, generators, imports, functions, classes, inheritance, magic methods, and profiling. It also includes code examples and explanations for each topic.

What you will learn

  • What is the purpose of profiling in Python?
  • What is the difference between imports and first-class functions in Python?
  • What are list comprehensions in Python?
  • How does inheritance and magic methods work in Python classes?
  • How do iterators and generators work in Python?

Typology: Study notes

2021/2022

Uploaded on 09/27/2022

kyran
kyran 🇬🇧

4.3

(7)

220 documents

1 / 37

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Plan%For%Python%Lecture%2
§Review
§List%Comprehensions
§Iterators,%Generators
§Imports
§Functions
§*args,%**kwargs,%first%class%functions
§Classes
§inheritance
§“magic”%methods%(objects%behave%like%builtAin%types)
§Profiling
§timeit
§cProfile
§Idioms
CIS%391%AFall%2015 Intro%to%AI 1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25

Partial preview of the text

Download Python Lecture Plan for Introduction to AI Course and more Study notes Voice in PDF only on Docsity!

Plan For Python Lecture 2

§ Review

§ List Comprehensions

§ Iterators, Generators

§ Imports

§ Functions

§ *args, **kwargs, first class functions

§ Classes

§ inheritance

§ “magic” methods (objects behave like built in types)

§ Profiling

§ timeit

§ cProfile

§ Idioms

Review

>>>import this

The Zen of Python, by Tim Peters

[x for x in lst1 if x > 2 for y in lst2 for z in lst if x + y + z < 8] res = [] # translation for x in lst1: if x > 2: for y in lst2: for z in lst3: if x + y + z > 8: res.append(x)

List Comprehension extra for

Iterators use memory efficiently

§ Iterators are objects with a next() method:

§ To be iterable: iter()

§ To be iterators: next()

k = [1,2,3] i = iter(k) # could also use k.iter() i.next() 1 i.next() 2 i.next() 3 i.next() StopIteration

Import Modules and Files

import math math.sqrt(9)

NOT:

from math import * sqrt(9) # unclear where function defined #hw1.py def concatenate(seqs): return [seq for seq in seqs] # This is wrong

run python interactive interpreter (REPL) in directory

with hw1.py

import hw assert hw1.concatenate([[1, 2], [3, 4 ]]) == [1, 2, 3, 4 ] #AssertionError reload(hw1) #after fixing hw

Functions

(Methods later)

Function overloading? No.

§ There is no function overloading in Python.

§ Unlike Java, a Python function is specified by its name alone

§ Two different functions can’t have the same name, even if they

have different numbers, order, or names of arguments.

§ But operator overloading – overloading +, ==, , etc. – is possible

using special methods on various classes (see later slides)

Default Values for Arguments

§ You can provide default values for a function’s arguments

§ These arguments are optional when the function is called

def myfun(b, c=3, d=“hello”): return b + c myfun(5,3,”bob”) 8 myfun(5,3) 8 myfun(5) 8

*args

§ Suppose you want to accept a variable number of

non keyword arguments to your function.

def print_everything(*args):

args is a tuple of arguments passed to the fn

for count, thing in enumerate(args): print '{0}. {1}'.format(count, thing)

lst = ['a', ’b', 'c’] print_everything(*lst)

  1. a

  2. b

  3. c

print_everything('a', ’b', 'c')

**kwargs

§ Suppose you want to accept a variable number of

keyword arguments to your function.

def print_keyword_args(**kwargs):

kwargs is a dict of the keyword args passed to the fn

for key, value in kwargs.iteritems(): #.items() is list print "%s = %s" % (key, value)

kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'} print_keyword_args(**kwargs) first_name = John last_name = Doe print_keyword_args(first_name="John”, last_name="Doe")

Combining ideas

foo(arg1, *args, **kwargs) # one mandatory argument

Default Arguments & Memoization

§ Default parameter values are evaluated only when

the def statement they belong to is executed.

§ The function uses the same default object each call

def fib(n, fibs={}): if n in fibs: return fibs[n] if n <= 1: fibs[n] = n else: fibs[n] = fib(n-1) + fib(n-2) return fibs[n]

First Class Functions

§ Functions are “first class citizens”

§ Pass functions as arguments to other functions,

§ returning functions as the values from other functions,

§ Assign functions to variables or store them in data structures

§ Higher order functions: take functions as input

**def compose(f, g, x): return f(g(x))

compose(str, sum, [1,2,3]) '6'**

Sorted list of n grams

from operator import itemgetter def calc_ngram(inputstring, nlen): ngram_list = [inputstring[x:x+nlen] for x in
xrange(len(inputstring)-nlen+1)] ngram_freq = {} # dict for storing results for n in ngram_list: # collect the distinct n-grams and count if n in ngram_freq: ngram_freq[n] += 1 else: ngram_freq[n] = 1 # human counting numbers start at 1

set reverse = False to change order of sort

(ascending/descending) return sorted(ngram_freq.iteritems(),
key=itemgetter(1), reverse=True) http://times.jayliew.com/2010/05/20/a simple n gram calculator pyngram/

Classes and Inheritance