James Tam Lists In this section of notes you will be introduced to new type of variable that consists of other types.

Slides:



Advertisements
Similar presentations
Introduction to arrays
Advertisements

James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type, one- dimensional arrays.
James Tam Multi-Dimensional Arrays In Pascal In this section of notes you will learn about how and when to use multi- dimensional arrays.
James Tam Advanced Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types.
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type, one- dimensional arrays.
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type, one- dimensional arrays.
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type arrays.
James Tam Arrays In this section of notes you will be introduced to a composite type where all elements must be of the same type (homogeneous): arrays.
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
Chapter 10.
James Tam Multi-Dimensional Arrays In Pascal In this section of notes you will learn about how and when to use multi- dimensional arrays.
J. Michael Moore From James Tam’s material Multi-Dimensional Arrays CSCE 110.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
James Tam Functions: Decomposition And Code Reuse (Part I) This section of notes shows you how to write functions that can be used to: decompose large.
J. Michael Moore Arrays CSCE 110 From James Tam’s material.
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type, one- dimensional arrays.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
James Tam Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types that are.
J. Michael Moore From James Tam’s material Multi-Dimensional Arrays CSCE 110.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
James Tam Arrays / Lists In this section of notes you will be introduced to new type of variable that consists of other types.
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type, one- dimensional arrays.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
James Tam Multi-Dimensional Arrays In Pascal In this section of notes you will learn about how and when to use multi- dimensional arrays.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
J. Michael Moore Arrays CSCE 110. J. Michael Moore Typical (although simplified) Problem Write a program that will track student grades in a class. The.
Making Decisions In Python
James Tam Pointers In this section of notes you will learn about another type of variable that stores addresses rather than data.
Arrays (Part II). Two- and Multidimensional Arrays Two-dimensional array: collection of a fixed number of components (of the same type) arranged in two.
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
CS0007: Introduction to Computer Programming Introduction to Arrays.
Fundamentals of Python: From First Programs Through Data Structures
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Fundamentals of Python: First Programs
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Lists in Python.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
James Tam Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types that are.
A First Book of ANSI C Fourth Edition
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CHAPTER: 12. Array is a collection of variables of the same data type that are referenced by a common name. An Array of 10 Elements of type double.
DATA STRUCTURES LAB 1 TA: Nouf Al-harbi
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
James Tam Multi-Dimensional Arrays In Pascal In this section of notes you will learn about how and when to use multi- dimensional arrays.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Composite Types You will learn how to create new variables that are collections of other entities 1.
EKT150 : Computer Programming
Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types that are used for.
Starting Out with Programming Logic & Design
Arrays In this section of notes you will be introduced to a homogeneous composite type, one-dimensional arrays One-dimensional arrays in Pascal.
Arrays In this section of notes you will be introduced to a composite type where all elements must be of the same type (homogeneous): arrays Homogeneous.
Location Of The Online Examples
Presentation transcript:

James Tam Lists In this section of notes you will be introduced to new type of variable that consists of other types.

James Tam Types Of Variables Python variables 1.Simple (atomic) integer charboolean real Lists Strings Tuples, Dictionaries Classes 2. Aggregate (composite)

James Tam Types Of Variables Python variables 1.Simple (atomic) integer charboolean real Lists Strings Tuples, Dictionaries Classes 2. Aggregate (composite)

James Tam List In many programming languages a list is implemented as an array. Python lists have many of the characteristics of the arrays in other programming languages but they also have many other features. This section will talk about the features of lists that are largely common to arrays.

James Tam Example Problem Write a program that will track the percentage grades for a class of students. The program should allow the user to enter the grade for each student. Then it will display the grades for the whole class along with the average.

James Tam Why Bother With Composite Types? For the full version of the example look in UNIX under: /home/231/examples/lists/classList1.py CLASS_SIZE = 5 stu1 = 0 stu2 = 0 stu3 = 0 stu4 = 0 stu5 = 0 total = 0 average = 0 stu1 = input ("Enter grade for student no. 1: ") stu2 = input ("Enter grade for student no. 2: ") stu3 = input ("Enter grade for student no. 3: ") stu4 = input ("Enter grade for student no. 4: ") stu5 = input ("Enter grade for student no. 5: ")

James Tam Why Bother With Composite Types? (2) total = stu1 + stu2 + stu3 + stu4 + stu5 average = total / CLASS_SIZE print print "GRADES" print "The average grade is", average, "%" print "Student no. 1:", stu1 print "Student no. 2:", stu2 print "Student no. 3:", stu3 print "Student no. 4:", stu4 print "Student no. 5:", stu5

James Tam Why Bother With Composite Types? (2) total = stu1 + stu2 + stu3 + stu4 + stu5 average = total / CLASS_SIZE print print "GRADES" print "The average grade is", average, "%" print "Student no. 1:", stu1 print "Student no. 2:", stu2 print "Student no. 3:", stu3 print "Student no. 4:", stu4 print "Student no. 5:", stu5 NO!

James Tam What Were The Problems With The Previous Approach? Redundant statements. Yet a loop could not be easily employed given the types of variables that you have seen so far.

James Tam What’s Needed A composite variable that is a collection of another type. -The composite variable can be manipulated and passed throughout the program as a single entity. -At the same time each element can be accessed individually. What’s needed…an array / list!

James Tam Creating A List (No Looping) This step is mandatory in order to allocate memory for the array. Omitting this step (or the equivalent) will result in a syntax error. Format: = [,,... ] Example: percentages = [0.0, 0.0, 0.0, 0.0, 0.0] letters = [‘A’, ‘A’, ‘A’] names = [“James Tam”, “Stacey Walls”, “Jamie Smyth”]

James Tam Creating A List (With Loops) Step 1: Create a variable that is a reference to the list Format: = [] Example: classGrades = []

James Tam Creating A List (With Loops: 2) Step 2: Initialize the list with the elements General format: -Within the body of a loop create each element and then append the new element on the end of the list. Example: for i in range (0, 5, 1): classGrades.append (0)

James Tam Revised Version Using A List For a full example look in UNIX under: /home/231/examples/lists/classList2.py CLASS_SIZE = 5 i = 0 total = 0 average = 0 classGrades = [] for i in range (0, CLASS_SIZE, 1): classGrades.append(0)

James Tam Revised Version Using A List (2) for i in range (0, CLASS_SIZE, 1): print "Enter grade for student no.", (i+1), ":", classGrades[i] = input () total = total + classGrades[i] average = total / CLASS_SIZE print print "GRADES" print "The average grade is", average, "%" for i in range (0, CLASS_SIZE, 1): print "Student no.", (i+1)

James Tam Printing Lists Although the previous example stepped through each element of the list in order to display it’s contents onscreen if you want to quickly check the contents (and not worry about details like formatting ) then you can simply use a print statement as you would with any other variable. Example: print classGrades Output: [10, 20, 30, 40, 50]

James Tam Take Care Not To Exceed The Bounds Of The List RAM [0] [1] [2] [3] list OK ??? list = [0, 1, 2, 3] for i in range (0, 4, 1): print list [i], print print list [4] ???

James Tam One Way Of Avoiding An Overflow Of The List Use a constant in conjunction with the list. SIZE = 100 The value in the constant controls traversals of the list for i in range (0, SIZE, 1): myList [i] = raw_input ( “ Enter a value: ” ) for i in range (0, SIZE, 1): print myList [i]

James Tam One Way Of Avoiding An Overflow Of The List Use a constant in conjunction with the list. SIZE = The value in the constant controls traversals of the list for i in range (0, SIZE, 1): myList [i] = raw_input ( “ Enter a value: ” ) for i in range (0, SIZE, 1): print myList [i]

James Tam To manipulate an array you need to first indicate which list is being accessed -Done via the name of the list e.g., “ print classGrades ” If you are accessing a single element, you need to indicate which element that you wish to access. -Done via the list index e.g., “ print classGrades[1] ” Accessing Data In The List classGrades [0] [1] [2] [3] [4] classGrades [0] [1] [2] [3] [4] Using only the name of the list refers to the whole list Use the list name and a subscript (the ‘index’) refers to a single element

James Tam Important Things To Keep In Mind (What you should now): Lists are a composite type that can be decomposed into other types. Other important points: -Copying lists -Passing lists as parameters

James Tam Copying Lists A list variable is not actually a list! Instead that list variable is actually a reference to the list. (This is important because if you use the assignment operator to copy from list to another you will end up with only one list). Example: -The full version can be found in UNIX under: /home/231/examples/lists/copy1.py list1 = [1,2] list2 = [2,1] print list1, list2 list1 = list2 print list1, list2 list1[0] = 99 print list1, list2

James Tam Copying Lists (2) To copy the elements of one list to another a loop is needed to copy each successive elements. Example: -The full version can be found in UNIX under: -/ home/231/examples/lists/copy2.py list1 = [1,2,3,4] list2 = [] for i in range (0, 4, 1): list2.append(list1[i]) print list1, list2 list1[1] = 99 print list1, list2

James Tam Parameter Passing What you’ve seen so far: -Passing a parameter into a function makes a local copy of the value passed in. -This is referred to as PASS BY VALUE. -Changes made to the parameter will only be made to the local copy and not the original.

James Tam Parameter Passing (2) Passing lists into functions is done using a different mechanism -When a list is passed into the function a local reference refers to the original list. -Example: -The full version can be found in UNIX under: /home/231/examples/lists/parameter1.py def fun (list): list[0] = 99 print list def main (): list = [1,2,3] print list fun (list) print list main () -Changes made to the local reference will change the original list. -This parameter passing mechanism is referred to as PASS BY REFERENCE (the local reference refers to the original list)

James Tam Parameter Passing (3) Exception: if the local reference is assigned to another list then it will obviously no longer refer to the original list. (Effect: changes made via the local reference will change the local list and not the original that was passed into the function). Example: The full version of the program can be found in UNIX under: /home/231/examples/lists/parameter2.py def fun (list): list = [3,2,1] print list def main (): list = [1,2,3] print list fun (list) print list main ()

James Tam When To Use Lists Of Different Dimensions Determined by the data – the number of categories of information determines the number of dimensions to use. Examples: (1D array) -Tracking grades for a class -Each cell contains the grade for a student i.e., grades[i] -There is one dimension that specifies which student’s grades are being accessed (2D array) -Expanded grades program -Again there is one dimension that specifies which student’s grades are being accessed -The other dimension can be used to specify the lecture section One dimension (which student)

James Tam When To Use Lists Of Different Dimensions (2) (2D list continued) Student Lecture section First student Second student Third student … L01 L02 L03 L04 L05 : L0N

James Tam When To Use Lists Of Different Dimensions (3) (2D list continued) Notice that each row is merely a 1D list (A 2D list is a list containing rows of 1D lists) L02 L07 L01 L03 L04 [0][1][2][3] [0] [1] [2] [3] [4] [5] [6] Columns Rows L06 L05 Important: List elements are specified in the order of [row] [column]

James Tam Creating And Initializing A Multi-Dimensional List In Python General structure = [ [,,... ], [,,... ], ::: [,,... ] ] Rows Columns

James Tam Creating And Initializing A Multi-Dimensional List In Python (2) Example: matrix = [ [0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]] for r in range (0, 4, 1): for c in range (0, 3, 1): print matrix [r][c], print

James Tam Creating And Initializing A Multi-Dimensional List In Python (3) General structure (Using loops): Create a variable that refers to a 1D list. The outer loop traverses the rows. Each iteration of the outer loop creates a new 1D list. Then the inner loop traverses the columns of the newly created 1D list creating and initializing each element in a fashion similar to how a single 1D list was created and initialized. Example (Using loops): aGrid = []# Create a reference to the list for r in range (0, 3, 1):# Outer loop runs once for each row aGrid.append ([])# Create a row (a 1D list) for c in range (0, 3, 1):# Inner loop runs once for each column aGrid[r].append (" ")# Create and initialize each element (1D list)

James Tam Example 2D List Program: A Character-Based Grid You can find the full program in UNIX under: /home/231/examples/lists/grid.py import sys import random MAX_ROWS = 4 MAX_COLUMNS = 4 NO_COMBINATIONS = 10

James Tam A Character-Based Grid (2) def generateElement (temp): anElement = '?' if (temp >= 1) and (temp <= 6): anElement = ' ' elif (temp >= 7) and (temp <= 9): anElement = '*' elif (temp == 10): anElement = '.' else: print " >" print "<< Value should be 1-10 but random value is ", temp anElement = '!' return anElement

James Tam A Character-Based Grid (3) def initialize (aGrid): for r in range (0, MAX_ROWS, 1): for c in range (0, MAX_COLUMNS, 1): temp = random.randint (1, NO_COMBINATIONS) aGrid[r][c] = generateElement (temp)

James Tam A Character-Based Grid (4) def display (aGrid): for r in range (1, MAX_ROWS, 1): for c in range (1, MAX_COLUMNS, 1): sys.stdout.write(aGrid[r][c]) print def displayLines (aGrid): for r in range (0, MAX_ROWS, 1): print " " for c in range (0, MAX_COLUMNS, 1): sys.stdout.write ('|') sys.stdout.write (aGrid[r][c]) print '|' print " "

James Tam A Character-Based Grid (5) # MAIN FUNCTION aGrid = [] for r in range (0, MAX_ROWS, 1): aGrid.append ([]) for c in range (0, MAX_COLUMNS, 1): aGrid[r].append (" ") initialize(aGrid) print "Displaying grid" print "===============" display (aGrid) print print "Displaying grid with bounding lines" print "===================================" displayLines (aGrid)

James Tam Lists Can Be Treated As A Set That means that the ‘in’ operator can be used in conjunction with lists. Branching list = ["bob", "alice", "mary", "tom", "dick", "harry"] if ("tom" in list): print "tom is in" Loops list = [123, 43, 35, 1, 888, 666, 777] temp = 0 for temp in list: print temp

James Tam You Should Now Know Why and when a list should be used How to create and initialize a list How to access or change the elements of a list Issues associated with copying lists and passing lists as parameters into functions When to use lists of different dimensions How to use the ' in ' operator in conjunction with lists

James Tam After This Section You Should Now Know How to write the definition for a function -How to write a function call How to pass information to and from functions via parameters and return values How and why to declare variables locally How to test functions and procedures How to design a program from a problem statement -How to determine what are the candidate functions -How to determine what variables are needed and where they need to be declared -Some approaches for developing simple algorithms (problem solving techniques)