Introduction to Programming

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

CS107 Introduction to Computer Science Lecture 5, 6 An Introduction to Algorithms: List variables.
Week 7 - Programming II Today – more features: – Loop control – Extending if/else – Nesting of loops Debugging tools Textbook chapter 7, pages
A revision guide for programming with python. 1.A program is a set of instructions that tells a computer what to do. 2.The role of a programmer is to.
Programming for Linguists An Introduction to Python 24/11/2011.
Sequences Jordi Cortadella Department of Computer Science.
6 October 2015Birkbeck College, U. London1 Introduction to Computer Systems Lecturer: Steve Maybank Department of Computer Science and Information Systems.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
29 September 2015Birkbeck College, U. London1 Introduction to Computer Systems Lecturer: Steve Maybank Department of Computer Science and Information Systems.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
17 November 2015Birkbeck College1 Introduction to Computer Systems Lecturer: Steve Maybank Department of Computer Science and Information Systems
3 November 2015Birkbeck College, U. London1 Introduction to Computer Systems Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
8 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
+ Arrays & Random number generator. + Introduction In addition to arrays and structures, C supports creation and manipulation of the following data structures:
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
5 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Python Programing: An Introduction to Computer Science
24 November 2015Birkbeck College, U. London1 Introduction to Computer Systems Lecturer: Steve Maybank Department of Computer Science and Information Systems.
19 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
CPSC 233 Tutorial 5 February 2 th /3 th, Java Loop Statements A portion of a program that repeats a statement or a group of statements is called.
26 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
4 March 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems
Introduction to Programming Python Lab 8: Loops 26 February PythonLab8 lecture slides.ppt Ping Brennan
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
11 March 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems
Introduction to Programming
Introduction to Programming
Sections 10.1 – 10.4 Introduction to Arrays
Introduction to Computer Systems
Introduction to Programming
Introduction to Programming
Introduction to Programming
Introduction to Programming
Containers and Lists CIS 40 – Introduction to Programming in Python
Introduction to Computer Systems
Introduction to Programming
Introduction to Programming
Introduction to Programming
Introduction to Programming
Week 8 - Programming II Today – more features: Loop control
IPC144 Introduction to Programming Using C Week 2 – Lesson 1
Introduction to Programming
Introduction to Programming
Chapter 8 Arrays Objectives
Chapter 10 Lists.
Introduction to Programming
Introduction to Programming
Introduction to Programming
Introduction to Programming
Introduction to Programming
A Robust Data Structure
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
Introduction to Programming
Introduction to Programming
Announcements Lab 6 was due today Lab 7 assigned this Friday
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
Introduction to Programming
TM111 Introduction to computing and information technology 1
Topics Sequences Lists Copying Lists Processing Lists
Python Basics with Jupyter Notebook
JavaScript: Introduction to Scripting
Introduction to Programming
Introduction to Programming
CS Problem Solving and Object Oriented Programming Spring 2019
Introduction to Computer Science
Presentation transcript:

Introduction to Programming Department of Computer Science and Information Systems Tingting Han (afternoon), Steve Maybank (evening) tingting@dcs.bbk.ac.uk sjmaybank@dcs.bbk.ac.uk Autumn 2018 Week 11: Lists Birkbeck College, U. London

Mock In Lab Test: ahi Define the function ahi The function prints the prompt "Please enter your annual household income: “ The function returns an integer obtained from the keyboard. Birkbeck College 2

Mock In Lab Test: numberOfChildren Define the function numberOfChildren The function prints the prompt "Please enter the number of your children: " The function obtains an integer n from the keyboard. If n < 0, then an error message is printed: "Error: a number greater than or equal to 0 is required“ The prompt is repeated. If n ≥ 0, then n is returned. Birkbeck College 3

Mock In Lab Test: assistance Define the function assistance(a, nc), where a is the annual household income and nc is the number of children. If a>= $30,000 and a < $40,000, and nc >= 3, then assistance is $1,000 per child If a >= $20,000 and a < $30,000 and nc >= 2, then assistance is $1,500 per child If a < $20,000, then assistance is $2,000 per child In all other cases, assistance is 0 Birkbeck College 4

Lists A mechanism for collecting together multiple values. A way of allocating names to multiple variables. PFE Section 6.1 5

Creation of a List values = [32, 54, 67, 5] initial data name of list values[0] values[1] values[2] values[3] values = [32, 54, 67, 5] initial data name of list variable Names of variables: values[0], values[1], values[2], values[3] The numbers 0, 1, 2, 3 are indices print(values[2]) # prints 67 print(values) # prints entire list PFE Section 6.1 6

Indices and Length # prints 10 values = [32, 54, 67, 5] values[2] = 10 print(values[2]) #print 67 or 10? # prints 10 print(len(values)) #print 3 or 4? # there are 4 values, prints 4 as the list’s length print(values[-1]) # prints 5 Allowed negative indices are -1 to -len(values), i.e. -1, -2, -3, -4 PFE Section 6.2 7

Lists and for Loops Both these loops have the same effect for i in range(len(values)) : print(values[i]) for element in values : print(element) # the variable name element can be changed The iterative variable names i and element can be replaced with any sensible names. PFE Section 6.1.3 8

Bounds Error # bounds error values = [32, 54, 67, 5] values[len(values)] = 3 # bounds error # A bounds error causes a run time exception. # The error is not detected at compile time. PFE Section 6.1.2 9

List References scores = [10, 9, 7, 4, 5] values = scores scores[3] = 8 print(values[3]) # prints 8! # A list variable such as values is a pointer to the place # in memory where the list is stored. # values and scores both reference the same list of # numbers in memory. PFE Section 6.1.3 10

The List Variable as a Pointer scores = [10, 9, 7, 4, 5] values = scores scores list stored in memory values 10 9 7 4 5 The value of the variable scores is a pointer to the list. The value of the variable values is a pointer to the same list. PFE Section 6.1.3 11

Example values = [1, 2, "text", range] # Correct but not recommended. Where possible, # list elements should have the same type. PFE Section 6.1 12

Appending an Element friends = [] # empty list friends.append("Emily") friends.append("Bob") print(friends) # prints ["Emily", "Bob"] PFE Section 6.2.1 13

Inserting an Element # prints ["Harry", "Cindy", "Bob"] friends = ["Harry", "Bob"] friends.insert(1, "Cindy") print(friends) # prints ["Harry", "Cindy", "Bob"] friends.insert(i, "Emily") # i = 0, 1, 2: insert "Emily" before the element with index i # i = 3: insert "Emily" after "Bob" (same as append) PFE Section 6.2.2 14

Finding an Element # index of first occurrence: 1 if "Cindy" in friends : print("She's a friend") friends = ["Harry", "Emily", "Emily"] n = friends.index("Emily") # index of first occurrence: 1 n = friends.index("Tom") # error, run time exception PFE Section 6.2.3 15

Removing an Element friends = ["Harry", "Cindy", "Emily", "Bob"] name = friends.pop(1) print(name) # prints "Cindy" print(friends) # prints ["Harry", "Emily", "Bob"] friends.pop() # remove the last element "Bob" # prints ["Harry", "Emily"] PFE Section 6.2 16

Removing Matches Remove all strings of length < 4 from the list words # the list words has been defined i = 0 while i < len(words) : # len(words) is the length of the list words word = words[i] if len(word) < 4 : # len(word) is the length of the string word words.pop(i) else : i = i+1 PFE 6.3.7 17

Removing Matches 2 Remove all strings of length < 4 from the list words for i in range(len(words)): word = words[i] if len(word) < 4 : words.pop(i) # This code fails but why? words = [“a”, “b”, “c”] i=0, len(words)=3 pop(0) words = [“b”, “c”] i=1, len(words)=2 pop(1) words = [“b”] i=2, len(words)=1 In the for-loop, no matter whether it pops or not, i will increase anyway. in the while loop, i will only increase if it does not pop anything. PFE 6.3.7 18

Reading Input values = [] print("Please enter values, Q to quit: ") userInput = input("") while userInput != "Q" : values.append(float(userInput)) # The Shell looks like this Please enter values, Q to quit: 32 29 67.5 Q PFE 6.3.9 19

Quiz Score A final quiz score is computed by adding all the scores except for the lowest two. For example, if the scores are 8, 4, 7, 8.5, 9.5, 7, 5, 10 then the final score is 50. Write a program to compute the final score in this way. PFE How To 6.1 20

Solution def calScoreSum(scores): if len(scores) < 3 : #check whether there are at least three scores print("Too few scores. Please enter at least two scores.") else: scoreSum = 0 #sum of scores of ALL scores low1 = 101 #the lowest score, initially exceeding 100 (the max quiz score) low2 = 101 #the second lowest score for i in range(0, len(scores)): scoreSum = scoreSum + scores[i] #adding up all scores if scores[i] < low1: #replacing the lowest and second lowest when needed low2 = low1 low1 = scores[i] elif scores[i] < low2: low2 = scores[i] scoreSum = scoreSum - low1 - low2 print("The sum of scores is", scoreSum) PFE How To 6.1 21

Testing scores = [8,4,7,8.5,9.5,7,5,10] calScoreSum(scores) scores = [8,4,4,4,4] scores = [8,4] scores = [9] scores = [] PFE How To 6.1 22

Insert Suppose that values is a sorted list of integers. Write a function to insert a new value into its proper position. PFE R 6.19 23

Solution ## sortInsert inserts a new value into the proper position in a sorted list. #@param sortedIntList: a list of integers. We assume this list of integers is sorted in # an ascending order. #@param newInt: a new integer to be inserted #@return: the list of integers with the new value inserted. #Author: T. Han #Date: 8.12.2017 def sortInsert(sortedIntList, newInt): for i in range(len(sortedIntList)): if newInt < sortedIntList[i]: # the newInt is smaller than the ith element sortedIntList.insert(i,newInt) return sortedIntList sortedIntList.insert(len(sortedIntList),newInt) # the newInt is the largest PFE How To 6.1 24

Testing sortedIntList = [0,2,4,6] print(sortInsert(sortedIntList,0)) print(sortInsert(sortedIntList,1)) print(sortInsert(sortedIntList,3)) print(sortInsert(sortedIntList,4)) print(sortInsert(sortedIntList,6)) print(sortInsert(sortedIntList,7)) print(sortInsert([0,2,4,6],0)) print(sortInsert([0,2,4,6],1)) print(sortInsert([0,2,4,6],3)) print(sortInsert([0,2,4,6],4)) print(sortInsert([0,2,4,6],6)) print(sortInsert([0,2,4,6],7)) PFE How To 6.1 25