CSC 430 Lecture1: Introduction and Python Primer.

Slides:



Advertisements
Similar presentations
Piyush Kumar (Lecture 3: Stable Marriage) Welcome to COT5405.
Advertisements

Prof. Swarat Chaudhuri COMP 482: Design and Analysis of Algorithms Spring 2013 Lecture 2.
Telling a computer how to behave (via pseudocode -- a workaround for Computing’s Tower of Babel.) COS 116, Spring 2010 Adam Finkelstein.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Program Design and Development
Loops – While, Do, For Repetition Statements Introduction to Arrays
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Python Control of Flow.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
CSC 430 Lecture1: Introduction and Python Primer.
The Stable Marriage Problem
Introduction to Python
1 Chapter 1 Introduction: Some Representative Problems Slides by Kevin Wayne. Copyright © 2005 Pearson-Addison Wesley. All rights reserved.
1 Stable Matching Problem Goal. Given n men and n women, find a "suitable" matching. n Participants rate members of opposite sex. n Each man lists women.
Prof. Swarat Chaudhuri COMP 482: Design and Analysis of Algorithms Spring 2013.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
Input, Output, and Processing
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
If statements while loop for loop
CPS120: Introduction to Computer Science Decision Making in Programs.
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 The Stable Marriage Problem Algorithms and Networks 2014/2015 Hans L. Bodlaender Johan M. M. van Rooij.
CSC 107 – Programming For Science. The Week’s Goal.
Looping and Counting Lecture 3 Hartmut Kaiser
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
1 Chapter 1 Introduction: Some Representative Problems Slides by Kevin Wayne. Copyright © 2005 Pearson-Addison Wesley. All rights reserved.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
CS 106 Introduction to Computer Science I 09 / 26 / 2007 Instructor: Michael Eckmann.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
The Stable Marriage Problem
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
CSCI 256 Data Structures and Algorithm Analysis lecture 1 Some slides by Kevin Wayne copyright 2005, Pearson Addison Wesley all rights reserved, and some.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
CSCI 256 Data Structures and Algorithm Analysis Lecture 2 Some slides by Kevin Wayne copyright 2005, Pearson Addison Wesley all rights reserved, and some.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Information and Computer Sciences University of Hawaii, Manoa
Matching Boys Girls A B C D E
Stable Matching.
Chapter 1 Introduction: Some Representative Problems
Introduction to Python
Python: Control Structures
CSE 421: Introduction to Algorithms
Introduction to C++ Programming
S. Raskhodnikova; based on slides by K. Wayne
CS190/295 Programming in Python for Life Sciences: Lecture 6
CISC101 Reminders Assn 3 due tomorrow, 7pm.
String and Lists Dr. José M. Reyes Álamo.
CSE 421: Introduction to Algorithms
1.1 A First Problem: Stable Matching
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Chapter 1 Introduction: Some Representative Problems
CISC101 Reminders Assignment 3 due today.
Introduction to Python
Selamat Datang di “Programming Essentials in Python”
Presentation transcript:

CSC 430 Lecture1: Introduction and Python Primer

Today’s Class Syllabus What is Algorithm Design? A first algorithmic problem Lessons Learned Python Primer

What is Algorithm Design? Algorithm Design is the process of developing a step-by-step process that solves a general class of problems. Proper algorithm design includes: – Careful statement of the problem, and what an optimal (successful) solution looks like – Thorough specification of the algorithm, including data structures – Accurate analysis of the algorithm’s speed (runtime) – Proof of correctness that the algorithm always finds the correct solution to a problem

Algorithm Design vs. Hacking Algorithm Design 1.Think critically about the problem and how to solve it optimally. 2.Spend as much time as possible designing the algorithm with pencil-and- paper. 3.If it can be solved, carefully implement the algorithm, avoiding programming bugs. 4.Never touch it again. Hacking 1.Do your best to understand the problem in a few minutes/hours. 2.Start writing code immediately. 3.Stop when it seems to work. 4.(Optional) Try to make it run faster. 5.Fix it when it breaks, add a special case routine. 6.Fix it when it breaks again. 7.Fix it when it breaks again. 8.…

5 A First Problem: Stable Matching Problem: Given n men and n women, find a stable matching of marriage partners, if it exists – Participants rate members of opposite sex. – Each man lists women in order of preference from best to worst. – Each woman lists men in order of preference from best to worst. – A matching is stable in the sense that: everyone has exactly one partner (a perfect matching) nobody is willing to change marriage partners Zeus AmyClareBertha Yancey BerthaClareAmy Xavier AmyClareBertha 1 st 2 nd 3 rd Men’s Preference Profile favoriteleast favorite Clare XavierZeusYancey Bertha XavierZeusYancey Amy YanceyZeusXavier 1 st 2 nd 3 rd Women’s Preference Profile favoriteleast favorite

More on Matchings Perfect Matching Finding these are easy for this problem! Assume m == w then pick pairs until everyone is married Stable Matching X Prefers B to A B Prefers X to Y Is the matching on the left stable? X Y Z A B C X Y Z A B C

Brain Storm: How would you solve this problem? Remove or add people from the list? – Possible conflicts Think of it as a graph – If there are unstable pairs, then fix them Zeus AmyClareBertha Yancey BerthaClareAmy Xavier AmyClareBertha 1 st 2 nd 3 rd Men’s Preference Profile favoriteleast favorite Clare XavierZeusYancey Bertha XavierZeusYancey Amy YanceyZeusXavier 1 st 2 nd 3 rd Women’s Preference Profile favoriteleast favorite

Propose-and-reject algorithm. [Gale-Shapley 1962] Intuitive method that guarantees to find a stable matching. 8 Propose-And-Reject Algorithm Initialize each person to be free. while some man is free and hasn't proposed to every woman: Choose such a man m w = 1 st woman on m's list to whom m has not yet proposed if w is free: assign m and w to be engaged else if w prefers m to her fiancé m‘: assign m and w to be engaged, and m' to be free else: w rejects m

9 Proof of Correctness: Termination Observation 1. Men propose to women in decreasing order of preference. Observation 2. Once a woman is matched, she never becomes unmatched; she only "trades up." Claim. Algorithm terminates after at most n 2 iterations of while loop. Pf. Each time through the while loop a man proposes to a new woman. There are only n 2 possible proposals. Wyatt Victor 1 st A B 2 nd C D 3 rd C B AZeus Yancey XavierC D A B B A D C 4 th E E 5 th A D E E D C B E Bertha Amy 1 st W X 2 nd Y Z 3 rd Y X VErika Diane ClareY Z V W W V Z X 4 th V W 5 th V Z X Y Y X W Z n(n-1) + 1 proposals required

10 Proof of Correctness: Perfection Claim. All men and women get matched. Pf. (by contradiction) – Suppose, for sake of contradiction, that Zeus is not matched upon termination of algorithm. – Then some woman, say Amy, is not matched upon termination. – By Observation 2, Amy was never proposed to. – But, Zeus proposes to everyone, since he ends up unmatched. ▪

11 Proof of Correctness: Stability Claim. The GS algorithm will produce no unstable pairs. Pf. (by contradiction) – Suppose Z-A is an unstable pair: each prefers each other to partner in Gale-Shapley matching S*. There are two ways that this can occur: – Case 1: Z never proposed to A.  Z prefers his GS partner to A.  Z-A is stable. – Case 2: Z proposed to A.  A rejected Z (right away or later)  A prefers her GS partner to Z.  Z-A is stable. – In either case A-Z is stable, a contradiction. ▪ Zeus-Bertha Yancey-Amy S*... men propose in decreasing order of preference women only trade up

12 Summary Stable matching problem. Given n men and n women, and their preferences, find a stable matching if one exists. Gale-Shapley algorithm. Guarantees to find a stable matching for any problem instance. We have only done specification and proof of correctness; runtime analysis covered next class.

PYTHON PRIMER

Python is… Easy to learn Interpreted, not compiled Good for: – Scripting – Rapid application development – Scientific computing A bracket-and-semicolon-free language(!) Includes several useful built-in types Very high-level Similar to writing pseudocode Really fun to code in

The Basics There are three ways to run python: – Interactively in the interpreter program – As a command-line script – As an executable script Mostly, you’ll stick with the interpreter, unless you are writing a real-world application You can try out _any_ language feature in the interpreter, without ever creating a file

Starting the Interpreter on Moe You all have accounts on moe.bw.edu Talk to me after class if you are not comfortable with logging in Once logged in, type ‘python3’ at the prompt Installing python on your own computer is easy, and recommended.

Running Code in Python Whether you use the interpreter, or a source file, Python will execute the code one line at a time, storing the result in memory and producing output if required. Python programs end in the extension.py To import foo.py in the interpreter: >>>import foo To reload a module in Python interpreter: >>> from imp import reload >>> reload(foo)

Steps to Learning a Programming Language 1.Write Hello World! 2.Learn the basic syntax 3.Learn about the primitive types 4.Learn to create/manipulate strings 5.Learn how to do arithmetic 6.Learn Flow control 7.Learn how to write a function 8.Learn at least one cool/unique thing about this language

Your First Program No matter what language it is, the first program you’ll always write in it is the hello world application This is because a program is useless unless it can create output! In Python 3: print("Hello world!")

Syntax Example No curly brackets – New scope indicated with a colon – Scope is determined by indentation No semi colons – Lines are ended by a newline (imagine that!) – If you want to continue a line, just add a backslash: print(“x is equal \ to “ + i) Parentheses are optional, except when calling functions x = 5 i = 5 #comments start with # if x == i : print(“x is equal to “ + i) else: print(“x was not equal to “ + i)

Declaring Variables You don’t! Variables are created when they are first given a value. You cannot refer to a variable until it has been assigned Python types are dynamic, but strongly-typed – Variables get their type at time of assignment – Once assigned, they must be treated like the expected type, or an exception will occur

The Primitive Types Python simplifies primitive types from what you are used to: – Integers – Floats (double precision) – Complex numbers (if you care) – strings (no chars) – Booleans: False = {False, None, anything equal to 0,any empty container} True = {True, and anything not listed above}

Creating and Manipulating Strings String literals are: – Concatenated with the + operator: >>> S = “he” + “llo” >>>S ‘hello’ – Indexable: >>> S[1] ‘e’ – Slice-able >>> S = “hello” >>> S[1:4] ‘ell’ – Immutable >>> S[1] = “G” ERROR – There is a lot more to learn about strings! Check the python documentation.

Arithmetic Arithmetic is greatly simplified in python 3.0 Resulting type is the most complicated type in the expression: – = 4 – = 4.0 Operators: {+ - * / % // **} Ints, floats evaluated like a mathematician would do it: = – 6 = 1 5 * 5 = /2 = % 2 = 1 5 / 2 = 2.5 ** is the power operator: 3**2 = 9 4**.5 = **(1/3) = 3 // is the integer division operator (sort of) – Actually, it rounds down the result of the division operator toward minus infinity – 5//2 = 2 – 3.5//2 = 1.0 – -3//2 = -2 Good rule to follow: for basic things you do, python will mostly do what you expect, but be careful if doing something out of the ordinary

Flow Control if/else/elif: if x == 1: print(“1”) elif x == 2: print(“2”) elif x == 3: print(“3”) else: print(“invalid”) While loops: x = 0 while x < 5: x += 1 For loops: – Iterate over a sequence, not counting based x = [1,2,3,4,5] for num in x: print(num) – To iterate over indices, use range(start = 0,finish) for i in range(len(x)): print(x[i]) There is more you can read about: – break – continue – pass – else clauses on loops

Writing Functions No return type specified – But all functions have a return value Returns ‘None’—python’s version of Null—for void functions All other basic mechanics should be familiar to you, but you might want to learn about the really cool function calling features in python def foo(arg1,arg2,arg3): return arg1/arg2 + arg3

Some Cool Python Features Lists: >>> L = [1,2,3,4,5] >>>L[2] 3 >>>L[2:4] [3,4,5] List Comprehensions: >>> L2 = [x**2 for x in L] >>> L2 [1,4,9,16,25] Tuples—Immutable lists >>> x1 = (1,2) >>> x2 = (5,6) #Assignment can be done in pairs >>> x,y = x1 Dictionaries >>>D = {} >>>D[“Ohio”] = “Columbus” >>>D[“Iowa”] = “DesMoines” Reading from a file is easy: f = open(‘foo.txt’,”r”) #looks like C, doesn’t it? for line in f: print(line)

More on Lists For a list L: – L = [] creates an empty list – L = [1,2,3] to initialize with values. Items can be a variable: L = [1,x,3] Lists can be nested: L = [1, [2,3], 4] (can use to make 2D arrays) – L.append(X) appends a single item – L.extend(L2) adds all items in L2 as items at the end of L – L1 + L2 produces the same result as L1.extend(L2) without changing L1 – Use len(L) to get the length – There is support for negative indexing: Using L above, L[-1] evaluates to 3

Slicing Many high-level languages include support for list slicing: – List slices are lists themselves – Use a colon to indicate a range: L[2:8] is a sub-list including indexes 2 – 7 – Leaving numbers out defaults to the beginning/end: L[:len(L)//2] is the first-half of a list L[len(L)//2:] is the second half – Negatives allowed here too X = “dropExtension.doc” X[:-4] evaluates to “dropExtension”