Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

Similar documents
The Pyth Language. Administrivia

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

TAIL RECURSION, SCOPE, AND PROJECT 4 11

Python for C programmers

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Collections. Lists, Tuples, Sets, Dictionaries

COMP 204: Sets, Commenting & Exceptions

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Data Structures. Lists, Tuples, Sets, Dictionaries

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Python Intro GIS Week 1. Jake K. Carr

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Exceptions & a Taste of Declarative Programming in SQL

Artificial Intelligence A Primer for the Labs

Beyond Blocks: Python Session #1

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY

Object Oriented Programming in Python 3

Python: common syntax

CSE : Python Programming

Intro. Scheme Basics. scm> 5 5. scm>

Python at Glance. a really fast (but complete) ride into the Python hole. Paolo Bellagente - ES3 - DII - UniBS

Lecture #12: Quick: Exceptions and SQL

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Python I. Some material adapted from Upenn cmpe391 slides and other sources

A Little Python Part 1. Introducing Programming with Python

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

Some material adapted from Upenn cmpe391 slides and other sources

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

C10552: Intro to Computation. Lecture 2 July 17, 2016

CS Programming Languages: Python

Examples for Programming Language Features

;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for

CS 11 Haskell track: lecture 1

Senthil Kumaran S

CS116 - Module 5 - Accumulative Recursion

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals

COMP 204: Sets, Commenting & Exceptions

CSC Software I: Utilities and Internals. Programming in Python

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

At full speed with Python

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University

Introduction to Python

Functional Programming. Pure Functional Programming

The current topic: Python. Announcements. Python. Python

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013

python 01 September 16, 2016

Part III Appendices 165

Python Programming: Lecture 2 Data Types

Introduction to Python

Types, lists & functions

61A Lecture 2. Friday, August 28, 2015

Table of Contents EVALUATION COPY

Python Development with PyDev and Eclipse -

Announcements for this Lecture

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Structure and Interpretation of Computer Programs

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

ITERATORS AND STREAMS 9

Python. Executive Summary

Functional Programming Languages (FPL)

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CS115 - Module 9 - filter, map, and friends

Physics 514 Basic Python Intro

Scheme as implemented by Racket

Here n is a variable name. The value of that variable is 176.

Homework 1. Notes. What To Turn In. Unix Accounts. Reading. Handout 3 CSCI 334: Spring, 2017

CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

And Parallelism. Parallelism in Prolog. OR Parallelism

CSCI 150 Exam 2 Solutions

Lab 7: OCaml 12:00 PM, Oct 22, 2017

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference

Scripting Languages. Python basics

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

CSC 533: Programming Languages. Spring 2015

Rapid Application Development with

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

CS 415 Midterm Exam Spring 2002


Lecture 16: Static Semantics Overview 1

MUTABLE LISTS AND DICTIONARIES 4

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

CSCC24 Functional Programming Scheme Part 2

Introduction to Python

A Brief Introduction to Scheme (I)

CSE413 Midterm. Question Max Points Total 100

Advanced Python. Executive Summary, Session 1

Introduction to Python! Lecture 2

Transcription:

Python Tutorial Lecture for EE562 Artificial Intelligence for Engineers 1

Why Python for AI? For many years, we used Lisp, because it handled lists and trees really well, had garbage collection, and didn t require type declarations. Lisp and its variants finally went out of vogue, and for a while, we allowed any old language, usually Java or C++. This did not work well. The programs were big and more difficult to write. A few years ago, the AI faculty started converting to Python. It has the object-oriented capabilities of Java and C++ with the simplicity for working with list and tree structures that Lisp had with a pretty nice, easy-touse syntax. I learned it with very little work. 2

Getting Started Download and install Python from www.python.org onto your computer. EE is updating to use Python 3. Python 2.7 works fine for plain search programs. We ll let you know about the game interface. Read Python as a Second Language, a tutorial that Prof. Tanimoto wrote for CSE 415 students: https://courses.cs.washington.edu/courses/cse41 5/18wi/uwnetid/Tanimoto-PSL.pdf 3

Python Data Types int 105 float 3.14159 str Selection:, a string bool True, False list [ apple, banana, orange ] tuple (3.2, 4.5, 6.3) dict { one : 1, two : 2} function lambda x:2*x builtin_function_ math.sqrt or_method 4

Interacting with Python $ python Python 2.7.5 (default, Nov 12 2013, 16:18:42) [GCC 4.8.2 20131017 (Red Hat 4.8.2-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 5 + 7 12 >>> x = 5 + 7 >>> x 12 >>> print('x = '+str(x)) x = 12 >>> x = 'apple' >>> x + x 'appleapple' >>> print('x is an '+x) x is an apple 5

Defining Functions >>> def sqr(x):... return x*x You have to indent the lines of the function... >>> sqr(5) 25 >>> sqr(75) 5625 >>> sqr(3.14) 9.8596 >>> sqr('notanumber') Nice trace for execution errors. Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in sqr TypeError: can't multiply sequence by non-int of type 'str' 6

Defining a Recursive Function >>> def factorial(n):... if n < 1:... return 0... if n == 1:... return 1... return n * factorial(n-1)... >>> >>> factorial(3) 6 >>> factorial(10) 3628800 >>> factorial(-1) 0 Bad Version: >>>def fact(n): if n==1: return 1 else: return n * fact(n-1) File "<stdin>", line 5, in fact... File "<stdin>", line 5, in fact File "<stdin>", line 5, in fact RuntimeError: maximum recursion depth exceeded 7

Scopes of Bindings: In general, declare global variables to save worry, required if you change them. Global y not needed here and we have two different z s. >>> x = 5 >>> y = 6 >>> z = 7 >>> def fee(x):... z = x + y... return z... >>> r = fee(2) >>> r 8 Global y used here to change y inside the function. >>> def foo(x):... global y... z = x + y... y = y + 1... return z... >>> q = foo(2) >>> q 8 >>> y 7 8

Lists We use lists heavily in AI. Lisp lists had two parts: car (the head or first element of the list) cdr (the tail or remainder of the list) Python is MUCH more versatile. Lists are like arrays in that you can refer to any element and yet you can also work with the head and tail and much more. 9

Lists >>> mylist = ['a', 'b', 'c'] >>> mylist[0] 'a >>> mylist[1] 'b' >>> mylist[1:] ['b', 'c'] >>> mylist[2:] ['c'] >>> mylist[-1] 'c >>> mylist.insert(3,'d') >>> mylist ['a', 'b', 'c', 'd'] car (or head) cdr (or tail) append How do you insert at the beginning? 10

Slices of Lists >>> mylist ['a', 'b', 'c', 'd'] >>> len(mylist) 4 >>> mylist[0:len(mylist)] ['a', 'b', 'c', 'd'] >>> mylist[0:len(mylist):2] ['a', 'c'] >>> mylist[::-1] ['d', 'c', 'b', 'a'] >>> mylist[1:]? go through mylist by ones go through mylist by twos go through mylist in reverse 11

Iterating through Lists >>> for e in mylist:... print('element is '+e)... element is a element is b element is c element is d >>> count = 0 >>> while count < len(mylist):... print(mylist[count])... count += 1... a b c d 12

Strings Strings work a lot like lists! >>> mystring = 'abcd' >>> mystring 'abcd' >>> mystring[0] 'a' >>> mystring[0:2] 'ab' >>> mystring[-1] 'd' >>> mystring[::-1] 'dcba' 13

Dictionaries Dictionaries give us look-up table capabilities. >>> translate = {} >>> translate['i'] = 'Ich' >>> translate['go'] = 'gehe' >>> translate['to'] = 'zu' >>> translate['doctor'] = 'Artz' >>> translate['the'] = 'der' >>> print(translate['i']) Ich How can we print the translation of I go to the doctor? Is it correct German? 14

Functional Programming Functions can be values that are assigned to variables or put in lists. They can be arguments to or returned by functions. They can be created dynamically at run time and applied to arguments. They don t have to have names. This is like the lambda capability of Lisp 15

Example of Function Creation >>> def make_adder(y):... return lambda x: x + y... >>> f4 = make_adder(4) >>> f4(5) 9 >>> f7 = make_adder(7) >>> f7(5) 12 What does this mean? This is actually pretty tame. One can construct strings and make them into functions, too. 16

Object-Oriented Programming Unlike Lisp, Python is an object-oriented language, so you can program much as you did in Java. class Coord: "2D Point Coordinates" def init (self, x=0, y=0): self.x = x self.y = y # def describe(self): return '('+str(self.x)+','+str(self.y)+')' # def euclid(self,p2): return ((self.x-p2.x)**2+(self.y-p2.y)**2)**0.5 17

Using the Coord Object >>> p1 = Coord(3,5) >>> p2 = Coord(2,7) >>> p1.describe() '(3,5)' >>> p2.describe() '(2,7)' >>> p1.euclid(p2) 2.23606797749979 >>> p2.euclid(p1) 2.23606797749979 18

Writing Methods class Coord: "2D Point Coordinates" def init (self, x=0, y=0): self.x = x self.y = y Write a method to add together two points and return a new point p3 = the sum of them def add(self, p2): 19

Main Program with Command Line Arguments import sys def add(a, b): return a+b # if name ==' main ': first = int(sys.argv[1]) second = int(sys.argv[2]) sum = add(first, second) print(str(sum)) python try.py 4 5 9 I stored this in file try.py 20