EECS 110: Lec 11: Indefinite Loops and Program Design

Slides:



Advertisements
Similar presentations
EECS 110: Lec 11: Indefinite Loops and Program Design Aleksandar Kuzmanovic Northwestern University
Advertisements

Computer Science 1620 Loops.
COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Introduction to Python
Advanced Decisions and Loops Chapter Some Simple Schoolroom Statistics.
An Introduction to Textual Programming
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
by Chris Brown under Prof. Susan Rodger Duke University June 2012
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
More on Functions (Part 2) Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
EECS 110: Lec 11: Indefinite Loops and Program Design Aleksandar Kuzmanovic Northwestern University
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Last Week if statement print statement input builtin function strings and methods for loop.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Input and typing trouble! print 'Please input a number of meters' meters = input() # get input from user cm = meters * 100 # convert to centimeters print.
Course A201: Introduction to Programming 09/30/2010.
Python - Selection Selection means selecting (or choosing) what to do next. Should I cycle to school, or ask for a lift? If it’s a sunny day I might cycle.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Loops ! We've seen variables change in-place before: [ x*6 for x in range(8) ] [ 0, 6, 12, 18, 24, 30, 36, 42 ] remember range ?
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
Data Types and Conversions, Input from the Keyboard CS303E: Elements of Computers and Programming.
Iteration. Iteration: Review  If you wanted to display all the numbers from 1 to 1000, you wouldn’t want to do this, would you? Start display 1 display.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
Data Types and Conversions, Input from the Keyboard If you can't write it down in English, you can't code it. -- Peter Halpern If you lie to the computer,
EECS 110: Lec 9: Review for the Midterm Exam Aleksandar Kuzmanovic Northwestern University
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Introduction to Programming Python Lab 7: if Statement 19 February PythonLab7 lecture slides.ppt Ping Brennan
More on Functions (Part 2) Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
GCSE COMPUTER SCIENCE Practical Programming using Python Lesson 4 - Selection.
CMSC201 Computer Science I for Majors Lecture 08 – Lists
Chapter 2 Writing Simple Programs
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
GCSE COMPUTER SCIENCE Practical Programming using Python
Repetitive Structures
EECS 110: Lec 12: Mutable Data
Introduction to Programming
CS1020 – Data Structures And Algorithms 1 AY Semester 2
EECS 110: Lec 9: Review for the Midterm Exam
Week of 12/12/16 Test Review.
Introduction to Python
Data Types and Conversions, Input from the Keyboard
Line Continuation, Output Formatting, and Decision Structures
Lesson 4 - Challenges.
Selection and Python Syntax
Python: Control Structures
Programming 101 Programming for non-programmers.
Engineering Innovation Center
Line Continuation, Output Formatting, and Decision Structures
EECS 110: Lec 10: Definite Loops and User Input
Input and typing trouble!
Validations and Error Handling
3. Decision Structures Rocky K. C. Chang 19 September 2018
Introduction to Programming
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Conditional and iterative statements
Python programming exercise
CISC101 Reminders All assignments are now posted.
Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg
Making decisions with code
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Introduction to Programming
Iteration – While Loops
Year 8 Computer Science Digital Portfolio
Introduction to Python
Presentation transcript:

EECS 110: Lec 11: Indefinite Loops and Program Design Aleksandar Kuzmanovic Northwestern University http://networks.cs.northwestern.edu/EECS110-s17/

Final Exam When: Where: Time: Wednesday 5/31/17 Pancoe Life Science Pavilion (PLSAUD) Time: 9:30AM – 11:30AM

Python and images for creating and saving images import bmp.py image = BitMap( 300, 200, Color.GREEN ) creates a bitmap object and names it image

Python and images import bmp.py for creating and saving images image = BitMap( 300, 200, Color.GREEN ) creates a bitmap object and names it image objects are software abstractions containing structured information

Python and images and objects import bmp.py image = BitMap( 300, 200, Color.GREEN ) here, a bitmap object named image is calling an internal method named saveFile image.saveFile( "test.bmp" ) objects are variables that can contain their own functions, often called methods

Python and images and objects import bmp.py image = BitMap( 300, 200, Color.GREEN ) image.setPenColor( Color.Red ) two more internal methods image.plotPixel( 150, 100 ) image.saveFile( "test.bmp" ) objects are variables that can contain their own functions, often called methods

Q: What does this plot? from bmp import * def test(): """ image demonstration """ width = 200 height = 200 image = BitMap( width, height ) # a 2d loop over each pixel for col in range(width): for row in range(height): if col == row: image.plotPoint( col, row ) image.saveFile( "test.bmp" )

A: A diagonal in the SW -> NE direction Q: What does this plot? A: A diagonal in the SW -> NE direction from bmp import * def test(): """ image demonstration """ width = 200 height = 200 image = BitMap( width, height ) # a 2d loop over each pixel for col in range(width): for row in range(height): if col == row: image.plotPoint( col, row ) image.saveFile( "test.bmp" )

How could you change this code so that it plots a diagonal from NW to SE? def test(): """ demonstrating images """ width = 200 height = 200 image = BitMap( width, height ) # a 2d loop over each pixel for col in range(width): for row in range(height): if col == row: image.plotPoint( col, row ) image.saveFile( "test.bmp" )

How could you change this code so that it plots a diagonal from NW to SE? def test(): """ demonstrating images """ width = 200 height = 200 image = BitMap( width, height ) # a 2d loop over each pixel for col in range(width): for row in range(height): if col == height – row -1: image.plotPoint( col, row ) image.saveFile( "test.bmp" )

Input and typing trouble! print('Please input a number of meters’) meters = input() # get input from user cm = meters * 100 # convert to centimeters print('That is', cm, 'cm.’) # print out the result

Input and typing trouble! print('Please input a number of meters') meters = input() # get input from user cm = meters * 100 # convert to centimeters print('That is', cm, 'cm.’) # print out the result >>> Please input a number of meters 5 That is 5555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555 cm. What is python thinking ?!?

Fix #1: use a type converter print('Please input a number of meters’) meters = int(input()) cm = meters * 100 print('That is', cm, 'cm.') check out my newly installed int converter! 1 100 The type of variable (box) matters! name: meters type: int name: cm type: int

Fix #1: use a type converter print('Please input a number of meters') meters = int(input()) # get int input from user cm = meters * 100 print('That is', cm, 'cm.') print('Please input a number of meters') meters = float(input()) # get float input from user cm = meters * 100 print('That is', cm, 'cm.') str converts to string type

s ='gattacaaggtaaaatgca' More with Loopy thinking s ='gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 How could we find the number of 'a's ? How about 'a's or 't's? How could we find the number of 'ta's ? How could we find the longest sequence of 'a's ?

s ='gattacaaggtaaaatgca' Loopy thinking s ='gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 How could we find the number of 'a's ? How about 'a's or 't's? How could we find the number of 'ta's ? How could we find the longest sequence of 'a's ?

s ='gattacaaggtaaaatgca' Loopy thinking s ='gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a': N = N + 1 print('N is', N) How could we find the number of 'a's ? How about 'a's or 't's? How could we find the number of 'ta's ? How could we find the longest sequence of 'a's ?

s = 'gattacaaggtaaaatgca' Loopy thinking s = 'gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 How could we find the number of 'a's ? How about 'a's or 't's? How could we find the number of 'ta's ? How could we find the longest sequence of 'a's ?

s = 'gattacaaggtaaaatgca' Loopy thinking s = 'gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a' or s[i] == 't': N = N + 1 print('N is', N) How could we find the number of 'a's ? How about 'a's or 't's? How could we find the number of 'ta's ? How could we find the longest sequence of 'a's ?

s ='gattacaaggtaaaatgca' Loopy thinking s ='gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 How could we find the number of 'a's ? How about 'a's or 't's? How could we find the number of 'ta's ? How could we find the longest sequence of 'a's ?

s ='gattacaaggtaaaatgca' Loopy thinking s ='gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 s = 'gattacaaggtaaaatgca' N = 0 for i in range(1,len(s)): if s[i] == 'a' and s[i-1] == 't': N = N + 1 print('N is', N) How could we find the number of 'a's ? How about 'a's or 't's? How could we find the number of 'ta's ? How could we find the longest sequence of 'a's ?

s ='gattacaaggtaaaatgca' Loopy thinking s ='gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 s = 'gattacaaggtaaaatgca' N = 0 for i in range(1,len(s)): if s[i] == 'a' and s[i-1] == 't': N = N + 1 print('N is', N) How could we find the number of 'a's ? How about 'a's or 't's? How could we find the number of 'ta's ? How could we find the longest sequence of 'a's ?

s ='gattacaaggtaaaatgca' Loopy thinking s ='gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 How could we find the longest sequence of 'a's ?

s ='gattacaaggtaaaatgca‘ Loopy thinking s ='gattacaaggtaaaatgca‘ - Len of current run - Len of best run 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 How could we find the longest sequence of 'a's ?

s ='gattacaaggtaaaatgca' Planning in "pseudocode" s ='gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Keep track of CurRun, MaxRun Loop through the string: if we do see an 'a' if the PREVIOUS letter is NOT an 'a' if the PREVIOUS letter IS an 'a'

s ='gattacaaggtaaaatgca' Planning in "pseudocode" s ='gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Keep track of CurRun, MaxRun Loop through the string: if we do see an 'a' if the PREVIOUS letter is NOT an 'a' Start a Run! CurRun = 1 if the PREVIOUS letter IS an 'a' Continue our run! CurRun = CurRun + 1 Check for a new maximum…

s ='gattacaaggtaaaatgca' Planning in "pseudocode" s ='gattacaaggtaaaatgca' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 MAX = 0 cur = 0 for i in range(0,len(s)): if s[i] == 'a': if s[i-1] != 'a': cur = 1 else: cur = cur + 1 if cur > MAX: MAX = cur print('Max is', MAX) Keep track of CurRun, MaxRun Loop through the string: if we do see an 'a' if the PREVIOUS letter is NOT an 'a' Start a Run! if the PREVIOUS letter IS an 'a' Continue our run! Check for a new maximum…

Summary 1 2 4 3 s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a': N = N + 1 print('N is', N) 2 s = 'gattacaaggtaaaatgca' N = 0 for i in range(0,len(s)): if s[i] == 'a' or s[i] == 't': N = N + 1 print('N is', N) 4 s = 'gattacaaggtaaaatgca' MAX = 0 cur = 0 for i in range(0,len(s)): if s[i] == 'a': if s[i-1] != 'a': cur = 1 else: cur = cur + 1 if cur > MAX: MAX = cur print 'Max is', MAX) 3 s = 'gattacaaggtaaaatgca' N = 0 for i in range(1,len(s)): if s[i] == 'a' and s[i-1] == 't': N = N + 1 print('N is', N)

for while Loops definite iteration indefinite iteration For a known number of iterations For an unknown number of iterations

Seeing into the future… def menu(): choice = 1 # Anything except 9 while choice != 9: print("I see danger in your future...") printMenu() choice = input("Make your choice ") print("The inner eye can see no more") def printMenu(): print("What would you like to do?") print("\t 0: See another prediction") print("\t 9: Quit") "\t " represents a tab

Gimme a break break stops the execution of the current loop I'll figure out later how to get out of this loop! def menu(): while True: print("I see danger in your future...”) printMenu() choice = int(input("Make your choice ")) if choice == 9: break print("The inner eye can see no more") def printMenu(): print("What would you like to do?") print("\t 0: See another prediction") print("\t 9: Quit") OK – I'll stop the loop now and continue with the code after the loop break stops the execution of the current loop

Indefinite Loops + input A problem this week ask you to repeatedly interact with the user (TTSecurities) What would you like to do? 0: Enter a new list 1: Print the current list 2: Find the average 9: Quit Please enter your choice The user's choice controls what happens

Indefinite Loops + input def menu(): choice = 1 while choice != 9: printMenu() choice = int(input("Please enter your choice ")) if choice == 0: print("You chose to enter a new list”) elif choice == 1: print("You chose to print the list") elif choice == 2: print("You chose to find this average of the list") elif choice != 9: print("You made an invalid choice") print("Goodbye!") def printMenu(): print("What would you like to do?") print("\t 0: Enter a new list") print("\t 1: Print the current list") print("\t 2: Find the average") print("\t 9: Quit")

if vs elif What happens if we change the elifs to ifs? def menu(): choice = 1 while choice != 9: printMenu() choice = int(input("Please enter your choice ")) if choice == 0: print("You chose to enter a new list") if choice == 1: print("You chose to print the list") if choice == 2: print("You chose to find this average of the list") if choice != 9: print("You made an invalid choice") print("Goodbye!”) What happens if we change the elifs to ifs?

Indefinite Loops + input def menu(): choice = 1 L = [] while choice != 9: printMenu() choice = int(input("Please enter your choice ")) if choice == 0: L = getNewList() elif choice == 1: printList(L) elif choice == 2: averageList(L) elif choice != 9: print("You made an invalid choice") print("Goodbye!") def getNewList(): print("You chose to get a new list") return [] Making a function for each choice makes the code cleaner and easier to modify

Gimme another break def menu(): choice = 1 L = [] while True: printMenu() choice = int(input("Please enter your choice ")) if choice == 0: L = getNewList() elif choice == 1: printList(L) elif choice == 2: averageList(L) elif choice == 9: break else: print("You made an invalid choice") print("Goodbye!”)

The Price Is Right! Goal: Buy from a set of 5 items (as many of each as you want) while spending between $9.25 and $10.00.

Step 1: Identify Information To Store What information does this program need to keep track of? Money you have spent, how much each item is, Items, # items to buy, limits,

Step 1: Identify Information To Store How much has the user spent? float: money Which items are available? list of strings: items How much does each available item cost? list of floats: prices Which item did the user currently choose? int: choice How many of the currently chosen item does the user want? int: number Money you have spent, how much each item is, Items, # items to buy, limits,

Step 1: Identify Information To Store How much has the user spent? float: money Which items are available? [“coke”, “ramer”] list of strings: items How much does each available item cost? list of floats: prices Which item did the user currently choose? int: choice How many of the currently chosen item does the user want? int: number Money you have spent, how much each item is, Items, # items to buy, limits,

Step 1: Identify Information To Store How much has the user spent? float: money Which items are available? [“coke”, “ramer”] list of strings: items How much does each available item cost? list of floats: prices [ 0.75, 0.25] Which item did the user currently choose? int: choice How many of the currently chosen item does the user want? int: number Money you have spent, how much each item is, Items, # items to buy, limits,

Step 2: Break Down Functionality What are the things that this program needs to do? Allow user to buy one item Ask user how many items to buy Update $$, update item list, check if finished

Step 2: Break Down Functionality Control the overall game play Prompt the user to enter a choice and number of items Calculate the total spent Figure out when the game is over Figure out win or lose Print a welcome message Remove the purchased item from the lists (items, prices) Allow user to buy one item Ask user how many items to buy Update $$, update item list, check if finished

ID problems, write on board Attempt 1 def playTry1(): print("Welcome to the price is right!") print("Your goal is to buy 5 or fewer items (any number of each)") print("and spend between $9.25 and $10") items = ["bleach","coke","ramen","ice cream","super ball"] prices = [1.35, .75, .25, 3.00, 1.75] money = 0.0 while money < 9.25 and len(items) > 0: print("You have spent $", money) printItems( items ) choice = int(input( "Which item would you like to buy? ")) number = int(input( "How many "+items[choice]+" would you like?")) print(items[choice], "is $", prices[choice]) money += prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] if money >= 9.25 and money <= 10.0: print("You win!") else: print("You lose!”) ID problems, write on board

"Quiz" part 1: Print Items Allow user to buy one item >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0 : coke 1 : pepsi 2 : sprite Allow user to buy one item Ask user how many items to buy Update $$, update item list, check if finished

ID problems, write on board Attempt 1 def playTry1(): print("Welcome to the price is right!") print("Your goal is to buy 5 or fewer items (any number of each)") print("and spend between $9.25 and $10") items = ["bleach","coke","ramen","ice cream","super ball"] prices = [1.35, .75, .25, 3.00, 1.75] money = 0.0 while money < 9.25 and len(items) > 0: print("You have spent $", money) printItems( items ) choice = int(input( "Which item would you like to buy? ")) number = int(input( "How many "+items[choice]+" would you like?")) print(items[choice], "is $", prices[choice]) money += prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] if money >= 9.25 and money <= 10.0: print("You win!") else: print("You lose!”) ID problems, write on board

ID problems, write on board Attempt 1: Issues def playTry1(): print("Welcome to the price is right!") print("Your goal is to buy 5 or fewer items (any number of each)") print("and spend between $9.25 and $10") items = ["bleach","coke","ramen","ice cream","super ball"] prices = [1.35, .75, .25, 3.00, 1.75] money = 0.0 while money < 9.25 and len(items) > 0: print("You have spent $", money) printItems( items ) choice = int(input("Which item would you like to buy? ")) number = int(input("How many "+items[choice]+" would you like?")) print(items[choice], "is $", prices[choice]) money += prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] if money >= 9.25 and money <= 10.0: print("You win!") else: print("You lose!”) ID problems, write on board Magic numbers!

ID problems, write on board Attempt 1a def playTry1a(): LIMIT_MIN = 9.25 LIMIT_MAX = 10.00 items = ["bleach","coke","ramen","ice cream","super ball"] prices = [1.35, .75, .25, 3.00, 1.75] money = 0.0 print("Welcome to the price is right!") print("Your goal is to buy", len(items), "or fewer items…") print("and spend between $", LIMIT_MIN, "and $", LIMIT_MAX) while money < LIMIT_MIN and len(items) > 0: print("You have spent $", money printItems( items ) choice = int(input("Which item would you like to buy? ")) number = int(input("How many "+items[choice]+" would you like?")) print(items[choice], "is $", prices[choice] ) money += prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] print("You have spent $", money) if money >= LIMIT_MIN and money <= LIMIT_MAX: print("You win!") else: print("You lose!”) ID problems, write on board

ID problems, write on board Attempt 1a: Issue def playTry1a(): LIMIT_MIN = 9.25 LIMIT_MAX = 10.00 items = ["bleach","coke","ramen","ice cream","super ball"] prices = [1.35, .75, .25, 3.00, 1.75] money = 0.0 print("Welcome to the price is right!") print("Your goal is to buy", len(items), "or fewer items…") print("and spend between $", LIMIT_MIN, "and $", LIMIT_MAX) while money < LIMIT_MIN and len(items) > 0: print("You have spent $", money) printItems( items ) choice = int(input("Which item would you like to buy? ”)) number = int(input("How many "+items[choice]+" would you like?”)) print(items[choice], "is $", prices[choice] ) money += prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] if money >= LIMIT_MIN and money <= LIMIT_MAX: print("You win!") else: print("You lose!”) ID problems, write on board Functionality is not broken out

Code is self-commenting. Each function does one specific thing. It's clear where we go to change aspects of the game. Code is self-commenting. def playBetter(): """ Play the game """ [items, prices] = initilizeItems() LIMIT_HIGH = 10.00 LIMIT_LOW = 9.25 money = 0.0 printIntro(LIMIT_LOW, LIMIT_HIGH, items) while not allDone(items, LIMIT_LOW, money): print("You have spent $", money) [items, prices, spent] = playRound(items, prices) money += spent winOrLose(money, LIMIT_LOW, LIMIT_HIGH) Functions can return more than one thing in a list

def playRound(items, prices): """ Play one round of the game Inputs: A list of items and a list of prices Returns: [items, prices, spent] where items is list of items remaining, prices is a list of remaining prices, and spent is the amount spent this round""" print("*********************”) printItems( items ) choice = int(input("Which item would you like to buy? ")) number = int(input("How many " + items[choice] +" would you like? ")) print(items[choice], "is $", prices[choice]) spent = prices[choice]*number prices = prices[0:choice] + prices[choice+1:] items = items[0:choice] + items[choice+1:] return [items, prices, spent]

(That is, you don’t have to get it perfect the first time) You CAN (and should) modify your code as you go to make it cleaner and better organized. (That is, you don’t have to get it perfect the first time) def playBetter(): """ Play the game """ [items, prices] = initilizeItems() LIMIT_HIGH = 10.00 LIMIT_LOW = 9.50 money = 0.0 printIntro(LIMIT_LOW, LIMIT_HIGH, items) while not allDone(items, LIMIT_LOW, money): print("You have spent $", money) [items, prices, spent] = playRound(items, prices) money += spent winOrLose(money, LIMIT_LOW, LIMIT_HIGH)

"Quiz" def diff( L ): def printItems( items ): Name(s):_______________________________ Return the min difference between any 2 elements in L Example: Print a list of strings with the specified format >>> diff([7, 0, 6, 4]) 1 Example: >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0 : coke 1 : pepsi 2 : sprite Only consider unsigned differences. You can assume at least 2 elements in the list Hint: use a NESTED loop def diff( L ): You need determine each element's index… def printItems( items ):

"Quiz" part 1: Print Items Allow user to buy one item >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0 : coke 1 : pepsi 2 : sprite Allow user to buy one item Ask user how many items to buy Update $$, update item list, check if finished

"Quiz" part 1: Print Items Allow user to buy one item >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0 : coke 1 : pepsi 2 : sprite def printItems(items): for x in range(len(items)): print(x,”:”,items[x]) Allow user to buy one item Ask user how many items to buy Update $$, update item list, check if finished

"Quiz" part 1: Print Items Allow user to buy one item >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0:coke 1:pepsi 2:sprite def printItems(items): for x in range(len(items)): print(str(x)+”:”+items[x]) , in print automatically puts blank space + removes blank space Allow user to buy one item Ask user how many items to buy Update $$, update item list, check if finished

Return the min difference between any 2 elements in L "Quiz" Part 2 Return the min difference between any 2 elements in L Example: >>> diff([7, 0, 6, 4]) 1 Only consider unsigned differences. You can assume at least 2 elements in the list Hint: use a NESTED loop def diff( L ):

Return the min difference between any 2 elements in L "Quiz" Part 2 Return the min difference between any 2 elements in L Example: >>> diff([7, 0, 6, 4]) 1 Only consider unsigned differences. You can assume at least 2 elements in the list Hint: use a NESTED loop def diff( L ): mindif = abs(L[1] – L[0]) for i in range(len(L)-1): for j in range(i+1,len(L)): d = abs(L[i]-L[j]) if d < mindiff: mindiff = d return mindif