CSc 110, Spring 2017 Lecture 19: more with lists

Slides:



Advertisements
Similar presentations
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Advertisements

1 Various Methods of Populating Arrays Randomly generated integers.
CS 106 Introduction to Computer Science I 02 / 29 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
1 Reference semantics. 2 A swap method? Does the following swap method work? Why or why not? public static void main(String[] args) { int a = 7; int b.
Lists in Python.
Topic 22 arrays - part 2 Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
I Power Higher Computing Software Development High Level Language Constructs.
EE 422C Day 2 Java, Eclipse. Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading:
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
Computing and the Web Algorithmic Thinking. Overview n Understanding a specific process n Developing an algorithm n Applying the algorithm to computer.
1 reading: 3.3 Using objects. Objects So far, we have seen: methods, which represent behavior variables, which represent data (categorized by types) It.
CSc 110, Autumn 2016 Lecture 15: lists Adapted from slides by Marty Stepp and Stuart Reges.
CSc 110, Autumn 2017 Lecture 13: Cumulative Sum and Boolean Logic
Adapted from slides by Marty Stepp and Stuart Reges
CSCI 162 – Introduction to Programming II William Killian
Building Java Programs
Lecture 13: More Arrays Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
CSc 110, Spring 2017 Lecture 14: Boolean Logic and Midterm Review
Dr. Kyung Eun Park Summer 2017
CSc 110, Autumn 2017 Lecture 23: lists as Parameters
CSc 110, Spring 2017 Lecture 6: Parameters (cont.) and Graphics
Arrays Part 1 Topic 19 - Stan Kelly-Bootle
Array traversals, text processing
CSc 110, Spring 2017 Lecture 8: input; if/else
CSE 143 Lecture 9 References and Linked Nodes reading: 3.3; 16.1
Building Java Programs
Building Java Programs Chapter 7
Building Java Programs
CSc 110, Spring 2017 Lecture 9: Advanced if/else; Cumulative sum
CSc 110, Spring 2017 Lecture 5: Constants and Parameters
CSc 110, Spring 2018 Lecture 9: Parameters, Graphics and Random
Building Java Programs
CSc 110, Autumn 2016 Lecture 19: lists as Parameters
Lecture 15: lists Adapted from slides by Marty Stepp and Stuart Reges
Lecture 22: lists Adapted from slides by Marty Stepp and Stuart Reges
CSc 110, Autumn 2017 Lecture 9: Graphics and Nested Loops
CSc 110, Autumn 2016 Lecture 5: Loop Figures and Constants
CSc 110, Spring 2017 Lecture 13: Random numbers and Boolean Logic
Topic 22 arrays - part 2 Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from
Defining methods and more arrays
Why did the programmer quit his job?
Building Java Programs
CSc 110, Spring 2018 Lecture 7: input and Constants
CSc 110, Spring 2018 Lecture 23: lists as Parameters
CSc 110, Spring 2018 Lecture 13: Cumulative Sum and Boolean Logic
Lecture 19: lists Adapted from slides by Marty Stepp and Stuart Reges
Lecture 10: Arrays AP Computer Science Principles
CSc 110, Spring 2018 Lecture 5: Loop Figures and Constants
Lecture 12: 2D Arrays AP Computer Science Principles
Lecture 10: Arrays II Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
References and objects
How many objects can you create by drawing in the circles?
Building Java Programs
Why did the programmer quit his job?
CSE 143 Lecture 5 References and Linked Nodes
CSc 110, Spring 2018 Lecture 10: More Graphics
CSc 110, Autumn 2017 Lecture 8: More Graphics
Suggested self-checks: Section 7.11 #1-11
slides created by Marty Stepp
Building Java Programs
Building Java Programs
slides adapted from Marty Stepp
Building Java Programs
slides created by Marty Stepp
Lecture 20 – Practice Exercises 4
slides created by Marty Stepp
Presentation transcript:

CSc 110, Spring 2017 Lecture 19: more with lists Adapted from slides by Marty Stepp and Stuart Reges

"Programs must be written for people to read, and only incidentally for machines to execute." Abelson and Sussman, Structure and Interpretation of Programs 2

Commenting Code Comments are required for homework as follows: - at the top of the program file - before each function - within a function when needed to clarify a point (see below) # Continue to loop until the user guesses the correct answer, # giving a clue each time while (guess != correct_answer): if (guess < correct_answer): print("It's higher.") else: print("It's lower.")

Lists and assignment Consider the following code: a1 = [4, 15, 8] a2 = a1 # a2 now refers to same list as a1 a2[0] = 7 print(a1) # [7, 15, 8] index 1 2 value 7 15 8 index 1 2 value 4 15 8 a1 a2

Reference semantics When a type has reference semantics, a variable holds a reference to a value rather than the value itself. Lists have reference semantics. Assigning a list to a variable causes the variable to hold a reference to the list Modifying a list element referenced by one variable will affect any other variables referencing the same list. a1 = [4, 15, 8] a2 = a1 # a2 now refers to same list as a1 a2[0] = 7 print(a1) # [7, 15, 8] index 1 2 value 7 15 8 index 1 2 value 4 15 8 a1 a2

Consider the following interaction with Idle: >>> b = a >>> print(b) [3, 7, 24] >>> b[0] = 88 >>> print(a) [88, 7, 24] >>> a[2] = 999 [88, 7, 999] >>> a = [10, 20, 30]

Reference semantics vs. Value semantics 7 7

Value semantics When a type has value semantics, a variable holds a copy of a value. ints, floats, strings and booleans in Python use value semantics. When an int, float, string, or boolean value is assigned to a variable, its value is copied into memory set aside for the variable. Assignment doesn't produces any sharing of data. Modifying the value of one variable does not affect others. x = 5 y = x y = 17 x = 8

Integers as parameters Function square squares its parameter. def square(x): x = x * x The value of variable a (of type int) is passed as an argument. def main(): a = 7 # can variable a be modified? square(a) print(str(a)) The variable a cannot be modified by square. It's basically not possible to write a swap method that accepts two ints. swap can't escape from itself to modify the outside world. (sort of like the villains in the holodeck on Star Trek; they can wreak havoc in their holo-world, but they can't leave and attack the real Enterprise outside.)

Lists as parameters Reference semantics apply not only to assignment but also to parameter passing. Changes made in the function are also seen by the caller. def main(): iq = [126, 167, 95] double_all(iq) print(iq) def double_all(a): for i in range(0, len(a)): a[i] = a[i] * 2 Output: [252, 334, 190] iq index 1 2 value 126 167 95 index 1 2 value 252 334 190 a

Objects as parameters Objects use reference semantics; the object is not copied. The parameter refers to the same object. If the parameter is modified, it will affect the original object. def main(): window = DrawingPanel(80, 50) window.canvas.create_rectangle(0, 0, 80, 50, fill="yellow") example(window) def example(panel): panel.canvas.create_rectangle(0, 0, 80, 50, fill="cyan") ... window Note: This is also the reason that it works when you pass the Graphics g as a parameter to a method, because it is drawing with the same pen object onto the same window. panel

Why reference semantics? sharing. It's useful to share an object's data among functions and methods. efficiency. Copying large amounts of data can be inefficient. f = open("population_data.txt") data = f.readlines() # data could be very large process(data) # a reference to data is passed in …

absolute_all Write a function absolute_all that accepts a list of integers and modifies it so that all its values are positive. a = [-2, 15, 25, -106] absolute_all(a) print(a) # [2, 15, 25, 106]

absolute_all # Changes all values of the list to # positive numbers. def absolute_all(x): for i in range(0, len(x)): x[i] = abs(x[i])

rotate Write a function rotate that takes a list and rotates the first element to the end of the list a = [10, 20, 30, 40] rotate(a) print(a) # [20, 30, 40, 10] Hint: Use list's append() method.

rotate # Rotates the list a by putting its first # element at the end of the list. def rotate(x): element = x.pop(0) x.append(element)

Problem: concat Write a function concat that accepts two lists and returns a new list containing all elements of the first list followed by all elements of the second. Note that this function returns a new list. a1 = [12, 34, 56] a2 = [7, 8, 9, 10] a3 = concat(a1, a2) print(a3) # [12, 34, 56, 7, 8, 9, 10] I probably won't reach this in lecture; it's here just in case.

concat: v1 # Returns a new list containing all elements of x # followed by all elements of y. def concat(x, y): result = [0] * (len(x) + len(y)) for i in range(0, len(x)): result[i] = x[i] for i in range(0, len(y)): result[len(x) + i] = y[i] return result Question: Can we make this simpler?

concat: v2 # Returns a new list containing all elements of x # followed by all elements of y. def concat(x, y): result = [] for item in x: result.append(item) for item in y: return result

Problem: concat3 Write a function concat3 that concatenates three lists similarly. a1 = [12, 34, 56] a2 = [7, 8, 9, 10] a3 = [444, 222, -1] print(concat3(a1, a2, a3)) # [12, 34, 56, 7, 8, 9, 10, 444, 222, -1] I probably won't reach this in lecture; it's here just in case.

concat3: v1 and v2 # Returns a new list containing all elements of x, y, and z. def concat3(x, y, z): result = [] for item in x: result.append(item) for item in y: for item in z: return result # Shorter version that calls concat. def concat3(a1, a2, a3): return concat(concat(a1, a2), a3) "When you hit a problem, you can lean forward and type or sit back and think." -- Dr. Proebsting

List reversal question Write a function that reverses the elements of a list. For example, if the list initially is this: [11, 42, -5, 27, 0, 89] Then the list becomes: [89, 0, 27, -5, 42, 11] Hint: think about swapping various elements...

Algorithm idea Swap pairs of elements from the edges; work inwards: index 1 2 3 4 5 value 89 27 -5 42 11 index 1 2 3 4 5 value 89 -5 27 42 11 index 1 2 3 4 5 value 11 42 -5 27 89 index 1 2 3 4 5 value 89 42 -5 27 11

Swapping values The red code should be replaced with: a = 7 b = 35 # swap a with b? a = b b = a print(str(a) + " " + str(b)) What is wrong with this code? What is its output? The red code should be replaced with: temp = a b = temp

Flawed algorithm What's wrong with this code? numbers = [11, 42, -5, 27, 0, 89] # reverse the list for i in range(0, len(numbers)): temp = numbers[i] numbers[i] = numbers[len(numbers) - 1 - i] numbers[len(numbers) - 1 - i] = temp The loop goes too far and un-reverses the array! Fixed version: for i in range(0, len(numbers) // 2):

reverse reverse – takes a list as a parameter and reverses it numbers = [11, 42, -5, 27, 0, 89] reverse(numbers) Solution: def reverse(numbers): for i in range(0, len(numbers) // 2): temp = numbers[i] numbers[i] = numbers[len(numbers) - 1 - i] numbers[len(numbers) - 1 - i] = temp