James Tam Arrays / 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.
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.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 14 – Student Grades Application: Introducing.
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.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 8 Multidimensional.
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type, one- dimensional arrays.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
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.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
James Tam Lists In this section of notes you will be introduced to new type of variable that consists of other types.
Arrays.
Introduction to C Programming CE Lecture 9 Data Structures Arrays.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
CPS120: Introduction to Computer Science Arrays. Arrays: A Definition A list of variables accessed using a single identifier May be of any data type Can.
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
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Arrays and 2D Arrays.  A Variable Array stores a set of variables that each have the same name and are all of the same type.  Member/Element – variable.
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.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 8 Multidimensional Arrays.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
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.
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 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.
Computer Programming for Engineers
Data Structure and Algorithm: CIT231 Lecture 3: Arrays and ADT DeSiaMore DeSiaMorewww.desiamore.com/ifm1.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
Python Fundamentals: Complex Data Structures Eric Shook Department of Geography Kent State University.
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.
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.
Introduction To Programming Information Technology , 1’st Semester
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.
Presentation transcript:

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 Types Of Variables Python variables 1.Simple (atomic) integer charstrings real Array / Lists Tuples, Dictionaries Classes 2. Aggregate (composite)

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

James Tam Arrays / Lists Arrays In most programming languages this composite type is referred to as an array. Lists The Python implementation of an array is a list. A list can be used and manipulated as an array (focus of this section). However the Python list is more powerful than a regular array (to be discussed in a later section).

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 a compilable example look in UNIX under: /home/courses/217/examples/arrays/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’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 An Array (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. General structure (Fixed sized array): = [,,... ] Example (Fixed sized array): 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 An Array (With Loops) Step 1: Create a variable that refers to an array Format: = [] Example: classGrades = []

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

James Tam Revised Version Using An Array For a full example look in UNIX under: /home/courses/217/tamj/examples/arrays/classList2.py CLASS_SIZE = 5 # Read: Step through the array an element at a time and get the user to input the # grades. def read (classGrades, average): total = 0 for i in range (0, CLASS_SIZE, 1): # Because array indices start at zero add one to the student number. temp = i + 1 print "Enter grade for student no.", temp, ":", classGrades[i] = input () total = total + classGrades[i] average = total / CLASS_SIZE return (classGrades, average)

James Tam Revised Version Using An Array (2) # Display: Traverse the array and display the grades. def display (classGrades, average): print print "GRADES" print "The average grade is", average, "%" for i in range (0, CLASS_SIZE, 1): # Because array indices start at zero add one to the student number. temp = i + 1 print "Student no.", temp, ":", classGrades[i], "%" # MAIN FUNCTION i = 0 temp = 0 average = 0 classGrades = [] for i in range (0, CLASS_SIZE, 1): classGrades.append(0) classGrades, average = read (classGrades, average) display (classGrades, average)

James Tam Take Care Not To Exceed The Bounds Of Arrays 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 An Array Use a constant in conjunction with arrays. SIZE = 100 The value in the constant determines the size of the array (this is an alternative way to create and initialize an array). myArray = [“^-^” for i in range (0, SIZE, 1)] The value in the constant controls traversals of the array for i in range (0, SIZE, 1): myArray [i] = raw_input (“Enter a value:”) for i in range (0, SIZE, 1): print myArray [i]

James Tam One Way Of Avoiding An Overflow Of An Array Use a constant in conjunction with arrays. SIZE = The value in the constant determines the size of the array (this is an alternative way to create and initialize an array). myArray = [“^-^” for i in range (0, SIZE, 1)] The value in the constant controls traversals of the array for i in range (0, SIZE, 1): myArray [i] = raw_input (“Enter a value:”) for i in range (0, SIZE, 1): print myArray [i]

James Tam To manipulate an array you need to first indicate which array is being accessed Done via the name of the array 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 array index e.g., “print classGrades[1]” Accessing Data In The Array classGrades [0] [1] [2] [3] [4] classGrades [0] [1] [2] [3] [4] Using only the name of the array refers to the whole array Use the array name and a subscript (the ‘index’) refers to a single element

James Tam When To Use Arrays 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 Arrays Of Different Dimensions (2) (2D array continued) Student Lecture section First student Second student Third student … L01 L02 L03 L04 L05 : L0N

James Tam When To Use Arrays Of Different Dimensions (3) (2D array continued) Notice that each row is merely a 1D array (A 2D array is an array containing rows of 1D arrays) L02 L07 L01 L03 L04 [0][1][2][3] [0] [1] [2] [3] [4] [5] [6] Columns Rows L06 L05

James Tam Creating And Initializing A Multi-Dimensional Array In Python General structure (Fixed sized array): = [ [,,... ], [,,... ], ::: [,,... ] ] Rows Columns

James Tam Creating And Initializing A Multi-Dimensional Array In Python (2) Example (Fixed sized array): 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 Array In Python (3) General structure (Variable sized array): Create a variable that refers to a 1D array. The outer loop traverses the rows. For each iteration of the outer loop create a new 1D array. Then with the inner loop traverse the columns of the newly created 1D array creating and initializing each element in a fashion similar to how a single 1D array was created and initialized. Example (Variable sized array): aGrid = []# Create a reference to an array for r in range (0, 3, 1):# Outer loop runs once for each row aGrid.append ([])# Create a row (a 1D array) for c in range (0, 3, 1):# Inner loop runs once for each column aGrid[r].append (" ")# Create and initialize each element (1D array)

James Tam Example 2D Array Program: A Character-Based Grid You can find the full program in Unix under: /home/courses/217/examples/arrays/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) return aGrid

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 (" ") aGrid = initialize(aGrid) print "Displaying grid" print "===============" display (aGrid) print print "Displaying grid with bounding lines" print "===================================" displayLines (aGrid)

James Tam You Should Now Know Why and when should an array be used How to create and initialize an array How to access or change the elements When to use arrays of different dimensions