Introduction to Programming with Python www python org

  • Slides: 106
Download presentation
Introduction to Programming with Python (www. python. org)

Introduction to Programming with Python (www. python. org)

Languages n Some influential ones: n FORTRAN n n COBOL n n business data

Languages n Some influential ones: n FORTRAN n n COBOL n n business data LISP n n science / engineering logic and AI BASIC n a simple language

Programming basics n n code or source code: The sequence of instructions in a

Programming basics n n code or source code: The sequence of instructions in a program. syntax: The set of legal structures and commands that can be used in a particular programming language. n output: The messages printed to the user by a program. n console: The text box onto which output is printed. n Some source code editors pop up the console as an external window, and others contain their own console window.

Compiling and interpreting n Many languages require you to compile (translate) your program into

Compiling and interpreting n Many languages require you to compile (translate) your program into a form that the machine understands. compile source code Hello. java n byte code Hello. class execute output Python is instead directly interpreted into machine instructions. interpret source code Hello. py output

Expressions n expression: A data value or set of operations to compute a value.

Expressions n expression: A data value or set of operations to compute a value. Examples: n Arithmetic operators we will use: n n 1 + 4 * 3 42 + - * / % ** addition, subtraction/negation, multiplication, division modulus, a. k. a. remainder exponentiation precedence: Order in which operations are computed. n * / % ** have a higher precedence than + 1 + 3 * 4 is 13 n Parentheses can be used to force a certain order of evaluation. (1 + 3) * 4 is 16

Integer division n When we divide integers with / , the quotient is also

Integer division n When we divide integers with / , the quotient is also an integer. 3 4 ) 14 12 2 n More examples: n n 52 27 ) 1425 135 75 54 21 35 / 5 is 7 84 / 10 is 8 156 / 100 is 1 The % operator computes the remainder from a division of integers. 3 4 ) 14 12 2 43 5 ) 218 20 18 15 3

Real numbers n Python can also manipulate real numbers. n n -15. 9997 42.

Real numbers n Python can also manipulate real numbers. n n -15. 9997 42. 0 2. 143 e 17 The operators + - * / % ** ( ) all work for real numbers. n n n Examples: 6. 022 The / produces an exact answer: 15. 0 / 2. 0 is 7. 5 The same rules of precedence also apply to real numbers: Evaluate ( ) before * / % before + - When integers and reals are mixed, the result is a real number. n Example: 1 / 2. 0 is 0. 5 n The conversion occurs on a per-operator basis. n n n 7 / 3 * 1. 2 + 3 / 2 2. 4 + 1 3. 4

Math commands n n Python has useful commands for performing calculations. Command name Description

Math commands n n Python has useful commands for performing calculations. Command name Description Constant Description abs(value) absolute value e 2. 7182818. . . ceil(value) rounds up pi 3. 1415926. . . cos(value) cosine, in radians floor(value) rounds down log(value) logarithm, base e log 10(value) logarithm, base 10 max(value 1, value 2) larger of two values min(value 1, value 2) smaller of two values round(value) nearest whole number sin(value) sine, in radians sqrt(value) square root To use many of these commands, you must write the following at the top of your Python program: from math import *

Variables n variable: A named piece of memory that can store a value. n

Variables n variable: A named piece of memory that can store a value. n Usage: n n Compute an expression's result, store that result into a variable, and use that variable later in the program. assignment statement: Stores a value into a variable. n Syntax: name = value n Examples: x n n 5 x = 5 gpa = 3. 14 gpa 3. 14 A variable that has been given a value can be used in expressions. x + 4 is 9 Exercise: Evaluate the quadratic equation for a given a, b, and c.

print n print : Produces text output on the console. n Syntax: print "Message"

print n print : Produces text output on the console. n Syntax: print "Message" print Expression n Prints the given text message or expression value on the console, and moves the cursor down to the next line. print Item 1, Item 2, . . . , Item. N n n Prints several messages and/or expressions on the same line. Examples: print "Hello, world!" age = 45 print "You have", 65 - age, "years until retirement" Output: Hello, world! You have 20 years until retirement

input n input : Reads a number from user input. n n You can

input n input : Reads a number from user input. n n You can assign (store) the result of input into a variable. Example: age = input("How old are you? ") print "Your age is", age print "You have", 65 - age, "years until retirement" Output: How old are you? 53 Your age is 53 You have 12 years until retirement n Exercise: Write a Python program that prompts the user for his/her amount of money, then reports how many Nintendo Wiis the person can afford, and how much more money he/she will need to afford an additional Wii.

Repetition (loops) and Selection (if/else)

Repetition (loops) and Selection (if/else)

The for loop n for loop: Repeats a set of statements over a group

The for loop n for loop: Repeats a set of statements over a group of values. n Syntax: for variable. Name in group. Of. Values: statements n n We indent the statements to be repeated with tabs or spaces. variable. Name gives a name to each value, so you can refer to it in the statements. group. Of. Values can be a range of integers, specified with the range function. Example: for x in range(1, 6): print x, "squared is", x * x Output: 1 squared 2 squared 3 squared 4 squared 5 squared is is is 1 4 9 16 25

range n The range function specifies a range of integers: n n - the

range n The range function specifies a range of integers: n n - the integers between start (inclusive) and stop (exclusive) It can also accept a third value specifying the change between values. n n range(start, stop) range(start, stop, step) - the integers between start (inclusive) and stop (exclusive) by step Example: for x in range(5, 0, -1): print x print "Blastoff!" Output: 5 4 3 2 1 Blastoff! n Exercise: How would we print the "99 Bottles of Beer" song?

Cumulative loops n Some loops incrementally compute a value that is initialized outside the

Cumulative loops n Some loops incrementally compute a value that is initialized outside the loop. This is sometimes called a cumulative sum = 0 for i in range(1, 11): sum = sum + (i * i) print "sum of first 10 squares is", sum Output: sum of first 10 squares is 385 n Exercise: Write a Python program that computes the factorial of an integer.

if n if statement: Executes a group of statements only if a certain condition

if n if statement: Executes a group of statements only if a certain condition is true. Otherwise, the statements are skipped. n n Syntax: if condition: statements Example: gpa = 3. 4 if gpa > 2. 0: print "Your application is accepted. "

if/else n if/else statement: Executes one block of statements if a certain condition is

if/else n if/else statement: Executes one block of statements if a certain condition is True, and a second block of statements if it is False. n n Syntax: if condition: statements else: statements Example: gpa = 1. 4 if gpa > 2. 0: print "Welcome to Mars University!" else: print "Your application is denied. " n Multiple conditions can be chained with elif ("else if"): if condition: statements else: statements

while n while loop: Executes a group of statements as long as a condition

while n while loop: Executes a group of statements as long as a condition is True. n n good for indefinite loops (repeat an unknown number of times) Syntax: while condition: statements n Example: number = 1 while number < 200: print number, number = number * 2 n Output: 1 2 4 8 16 32 64 128

Logic n Many logical expressions use relational operators: Operator n n Meaning Example Result

Logic n Many logical expressions use relational operators: Operator n n Meaning Example Result == equals 1 + 1 == 2 True != does not equal 3. 2 != 2. 5 True < less than 10 < 5 False > greater than 10 > 5 True <= less than or equal to 126 <= 100 False >= greater than or equal to 5. 0 >= 5. 0 True Logical expressions can be combined with logical operators: Operator Example Result and 9 != 6 and 2 < 3 True or 2 == 3 or -1 < 5 True not 7 > 0 False Exercise: Write code to display and count the factors of a number.

Text and File Processing

Text and File Processing

Strings n string: A sequence of text characters in a program. n Strings start

Strings n string: A sequence of text characters in a program. n Strings start and end with quotation mark " or apostrophe ' characters. n Examples: "hello" "This is a string" "This, too, is a string. n n It can be very long!" A string may not span across multiple lines or contain a " character. "This is not a legal String. " "This is not a "legal" String either. " A string can represent characters by preceding them with a backslash. tab character new line character quotation mark character backslash character n t n " \ n Example: n n n "Hellottheren. How are you? "

Indexes n Characters in a string are numbered with indexes starting at 0: n

Indexes n Characters in a string are numbered with indexes starting at 0: n n Example: name = "P. Diddy" index 0 1 character P . 2 3 4 5 6 7 D i d d y Accessing an individual character of a string: variable. Name [ index ] n Example: print name, "starts with", name[0] Output: P. Diddy starts with P

String properties n n len(string) - number of characters in a string str. lower(string)

String properties n n len(string) - number of characters in a string str. lower(string) str. upper(string) (including spaces) - lowercase version of a string - uppercase version of a string Example: name = "Martin Douglas Stepp" length = len(name) big_name = str. upper(name) print big_name, "has", length, "characters" Output: MARTIN DOUGLAS STEPP has 20 characters

raw_input n raw_input : Reads a string of text from user input. n Example:

raw_input n raw_input : Reads a string of text from user input. n Example: name = raw_input("Howdy, pardner. What's yer name? ") print name, ". . . what a silly name!" Output: Howdy, pardner. What's yer name? Paris Hilton. . . what a silly name!

Text processing n text processing: Examining, editing, formatting text. n n often uses loops

Text processing n text processing: Examining, editing, formatting text. n n often uses loops that examine the characters of a string one by one A for loop can examine each character in a string in sequence. n Example: for c in "booyah": print c Output: b o o y a h

Strings and numbers n ord(text) n n Example: ord("a") is 97, ord("b") is 98,

Strings and numbers n ord(text) n n Example: ord("a") is 97, ord("b") is 98, . . . Characters map to numbers using standardized mappings such as ASCII and Unicode. chr(number) n - converts a string into a number. - converts a number into a string. Example: chr(99) is "c" Exercise: Write a program that performs a rotation cypher. n e. g. "Attack" when rotated by 1 becomes "buubdl"

File processing n Many programs handle data, which often comes from files. n Reading

File processing n Many programs handle data, which often comes from files. n Reading the entire contents of a file: variable. Name = open("filename"). read() Example: file_text = open("bankaccount. txt"). read()

Line-by-line processing n Reading a file line-by-line: for line in open("filename"). readlines(): statements Example:

Line-by-line processing n Reading a file line-by-line: for line in open("filename"). readlines(): statements Example: count = 0 for line in open("bankaccount. txt"). readlines(): count = count + 1 print "The file contains", count, "lines. " n Exercise: Write a program to process a file of DNA text, such as: ATGCAATTGCTCGATTAG n Count the percent of C+G present in the DNA.

Graphics

Graphics

Drawing. Panel n To create a window, create a drawingpanel and its graphical pen,

Drawing. Panel n To create a window, create a drawingpanel and its graphical pen, which we'll call g : from drawingpanel import * panel = drawingpanel(width, height) g = panel. get_graphics(). . . (draw shapes here). . . panel. mainloop() n The window has nothing on it, but we can draw shapes and lines on it by sending commands to g. n Example: g. create_rectangle(10, 30, 60, 35) g. create_oval(80, 40, 50, 70) g. create_line(50, 90, 70)

Graphical commands Command n Description g. create_line(x 1, y 1, x 2, y 2)

Graphical commands Command n Description g. create_line(x 1, y 1, x 2, y 2) a line between (x 1, y 1), (x 2, y 2) g. create_oval(x 1, y 1, x 2, y 2) the largest oval that fits in a box with top-left corner at (x 1, y 1) and bottom -left corner at (x 2, y 2) g. create_rectangle(x 1, y 1, x 2, y 2) the rectangle with top-left corner at (x 1, y 1), bottom-left at (x 2, y 2) g. create_text(x, y, text="text") the given text at (x, y) The above commands can accept optional outline and fill colors. g. create_rectangle(10, 40, 22, 65, fill="red", outline="blue") n The coordinate system is y-inverted: (0, 0) (200, 100)

Drawing with loops n We can draw many repetitions of the same item at

Drawing with loops n We can draw many repetitions of the same item at different x/y positions with for loops. n The x or y assignment expression contains the loop counter, i, so that in each pass of the loop, when i changes, so does x or y. from drawingpanel import * window = drawingpanel(500, 400) g = window. get_graphics() for i in range(1, 11): x = 100 + 20 * i y = 5 + 20 * i g. create_oval(x, y, x + 50, y + 50, fill="red") window. mainloop() n Exercise: Draw the figure at right.

What's Next?

What's Next?

Arrays (Lists) in Python one thing after another

Arrays (Lists) in Python one thing after another

Problem n n Given 5 numbers, read them in and calculate their average THEN

Problem n n Given 5 numbers, read them in and calculate their average THEN print out the ones that were above average

Data Structure Needed n n Need some way to hold onto all the individual

Data Structure Needed n n Need some way to hold onto all the individual data items after processing them making individual identifiers x 1, x 2, x 3, . . . is not practical or flexible the answer is to use an ARRAY a data structure - bigger than an individual variable or constant

An Array (a List) n n You need a way to have many variables

An Array (a List) n n You need a way to have many variables all with the same name but distinguishable! In math they do it by subscripts or indexes n n x 1, x 2, x 3 and so on In programming languages, hard to use smaller fonts, so use a different syntax n x [1], x[0], table[3], point[i]

Semantics n numbered from 0 to n-1 where n is the number of elements

Semantics n numbered from 0 to n-1 where n is the number of elements 0 1 2 3 4 5

Properties of an array (list) n n n Heterogeneous (any data type!) Contiguous Have

Properties of an array (list) n n n Heterogeneous (any data type!) Contiguous Have random access to any element Ordered (numbered from 0 to n-1) Number of elements can change very easily (use method. append) Python lists are mutable sequences of arbitrary objects

Syntax n n Use [] to give initial value to, like x = [1,

Syntax n n Use [] to give initial value to, like x = [1, 3, 5] refer to individual elements n n uses [ ] with index in the brackets most of the time you don’t refer to the whole array as one thing, or just by the array name (one time you can is when passing a whole array to a function as an argument)

List Operations you know Operator <seq> + <seq> * <int-expr> <seq>[] len(<seq>) <seq>[: ]

List Operations you know Operator <seq> + <seq> * <int-expr> <seq>[] len(<seq>) <seq>[: ] for <var> in <seq>: <expr> in <seq> Meaning Concatenation Repetition Indexing Length Slicing Iteration Membership (Boolean)

Indexing an Array n The index is also called the subscript In Python, the

Indexing an Array n The index is also called the subscript In Python, the first array element always has subscript 0, the second array element has subscript 1, etc. n Subscripts can be variables – they have to have integer values nk = 4 n items = [3, 9, ’a’, True, 3. 92] n items[k] = 3. 92 n items[k-2] = items[2] = ‘a’ n

List Operations n Lists are often built up one piece at a time using

List Operations n Lists are often built up one piece at a time using append. nums = [] x = float(input('Enter a number: ')) while x >= 0: nums. append(x) x = float(input('Enter a number: ')) n Here, nums is being used as an accumulator, starting out empty, and each time through the loop a new value is tacked on.

List Operations Method Meaning <list>. append(x) Add element x to end of list. <list>.

List Operations Method Meaning <list>. append(x) Add element x to end of list. <list>. sort() Sort (order) the list. A comparison function may be passed as a parameter. <list>. reverse() Reverse the list. <list>. index(x) Returns index of first occurrence of x. <list>. insert(i, x) Insert x into list at index i. <list>. count(x) Returns the number of occurrences of x in list. <list>. remove(x) Deletes the first occurrence of x in list. <list>. pop(i) Deletes the ith element of the list and returns its value.

Using a variable for the size n n It is very common to use

Using a variable for the size n n It is very common to use a variable to store the size of an array SIZE = 15 arr = [] for i in range(SIZE): arr. append(i) n Makes it easy to change if size of array needs to be changed

Solution to starting problem SIZE = 5 n = [0]*SIZE total = 0 for

Solution to starting problem SIZE = 5 n = [0]*SIZE total = 0 for ct in range(SIZE): n[ct] = float(input("enter a number “)) total = total + n[ct] cont'd on next slide

Solution to problem - cont'd average = total / SIZE for ct in range(5):

Solution to problem - cont'd average = total / SIZE for ct in range(5): if n[ct] > average: print (n[ct])

Scope of counter in a for loop n The counter variable has usual scope

Scope of counter in a for loop n The counter variable has usual scope (body of the function it’s in) n n n for i in range(5): counter does exist after for loop finishes what‘s its value after the loop?

Initialization of arrays n n a = [1, 2, 9, 10] # has 4

Initialization of arrays n n a = [1, 2, 9, 10] # has 4 elements a = [0] * 5 # all are zero

Watch out index out of range! n n n Subscripts range from 0 to

Watch out index out of range! n n n Subscripts range from 0 to n-1 Interpreter WILL tell you if an index goes out of that range BUT the negative subscripts work as they do with strings (which are, after all, arrays of characters) x = [5]*5 x[-1] = 4 # x is [5, 5, 4]

Assigning Values to Individual Array Elements temps = [0. 0] * 5 m=4 temps[2]

Assigning Values to Individual Array Elements temps = [0. 0] * 5 m=4 temps[2] = 98. 6; temps[3] = 101. 2; temps[0] = 99. 4; temps[m] = temps[3] / 2. 0; temps[1] = temps[3] - 1. 2; // What value is assigned? 7000 99. 4 temps[0] 7004 7008 ? 98. 6 temps[1] temps[2] 7012 101. 2 temps[3] 7016 50. 6 temps[4]

What values are assigned? SIZE =5 temps = [0. 0]* SIZE for m in

What values are assigned? SIZE =5 temps = [0. 0]* SIZE for m in range(SIZE): temps[m] = 100. 0 + m * 0. 2 for m in range(SIZE-1, -1): print(temps[m]) 7000 7004 7008 7012 7016 ? ? ? temps[0] temps[1] temps[2] temps[3] temps[4]

Indexes n n n Subscripts can be constants or variables or expressions If i

Indexes n n n Subscripts can be constants or variables or expressions If i is 5, a[i-1] refers to a[4] and a[i*2] refers to a[10] you can use i as a subscript at one point in the program and j as a subscript for the same array later - only the value of the variable matters

Variable Subscripts temps = [0. 0]*5 m=3. . . What is temps[m + 1]

Variable Subscripts temps = [0. 0]*5 m=3. . . What is temps[m + 1] ? What is temps[m] + 1 ? 7000 100. 0 temps[0] 7004 7008 7012 7016 100. 2 100. 4 100. 6 100. 8 temps[1] temps[2] temps[3] temps[4]

Random access of elements n n Problem : read in numbers from a file,

Random access of elements n n Problem : read in numbers from a file, only single digits - and count them - report how many of each there were Use an array as a set of counters n n ctr [0] is how many zero's, ctr[1] is how many ones, etc. ctr[num] +=1 is the crucial statement

Parallel arrays n n n Sometimes you have data of different types that are

Parallel arrays n n n Sometimes you have data of different types that are associated with each other like name (string) and GPA (float) You CAN store them in the same array n n ar = [“John”, 3. 24, “Mary”, 3. 9, “Bob”, 2. 7] You can also use two different arrays "side by side"

Parallel arrays, cont'd for i in range(SIZE): name[i], gpa[i] = float(input(“Enter”)) n Logically the

Parallel arrays, cont'd for i in range(SIZE): name[i], gpa[i] = float(input(“Enter”)) n Logically the name in position i corresponds to the gpa in position i n Nothing in the syntax forces this to be true, you just have to program it to be so.

Parallel Arrays Parallel arrays are two or more arrays that have the same index

Parallel Arrays Parallel arrays are two or more arrays that have the same index range and whose elements contain related information, possibly of different data types EXAMPLE SIZE = 50 id. Number = [“ “]*SIZE hourly. Wage = [0. 0] *SIZE arrays parallel

SIZE = 50 id. Number = [“ “] *SIZE // Parallel arrays hold hourly.

SIZE = 50 id. Number = [“ “] *SIZE // Parallel arrays hold hourly. Wage =[0. 0] *SIZE // Related information id. Number[0] 4562 hourly. Wage[0] 9. 68 id. Number[1] 1235 hourly. Wage[1] 45. 75 id. Number[2] 6278 hourly. Wage[2] 12. 71 . . . id. Number[48] 8754 hourly. Wage[48] 67. 96 id. Number[49] 2460 hourly. Wage[49] 8. 97

Selection sort - 1 -d array Algorithm for the sort 1. find the maximum

Selection sort - 1 -d array Algorithm for the sort 1. find the maximum in the list 2. put it in the highest numbered element by swapping it with the data that was at that location 3. repeat 1 and 2 for shorter unsorted list - not including highest numbered location 4. repeat 1 -3 until list goes down to one

Find the maximum in the list # n is number of elements max =

Find the maximum in the list # n is number of elements max = a[0] # value of largest element # seen so far for i in range(1, n): # note start at 1, not 0 if max < a[i]: max = a[i] # now max is value of largest element in list

Find the location of the max = 0 # max is now location of

Find the location of the max = 0 # max is now location of the far for i in range(1, n): if a[max] < a[i]: max = i # now max is location of the largest in # array # largest seen so

Swap with highest numbered Remember element at right end of list is numbered n-1

Swap with highest numbered Remember element at right end of list is numbered n-1 temp = a[max] = a[n-1] = temp # there is a shorter way in Python!

The Python way! n n n The previous code of finding the max and

The Python way! n n n The previous code of finding the max and its location will work in ANY high-level language. Python has some nice functions and methods to make it easier! Let’s try that.

The Python Way To find the max of the whole list mx = max(a)

The Python Way To find the max of the whole list mx = max(a) loc = a. index(mx) Is using index SAFE here? If it doesn’t find mx in a, it will crash! But you just got mx from the list using the max function, so it IS in the list a. n

The Python Way n n The swap then becomes a[loc], a[n-1] = a[n-1], a[loc]

The Python Way n n The swap then becomes a[loc], a[n-1] = a[n-1], a[loc] Python “hides” the temporary third variable

Find next largest element and swap (generic way) max = 0; for i in

Find next largest element and swap (generic way) max = 0; for i in range(1, n-1): # note n-1, not n if a[max] < a[i]: max = i temp = a[max] = a[n-2] = temp

put a loop around the general code to repeat for n-1 passes for pss

put a loop around the general code to repeat for n-1 passes for pss in range(n, 1, -1): max = 0 for i in range(1, pss): if a[max] <= a[i]: max = i temp = a[max] = a[pss-1] = temp

The whole thing the Python way for pss in range(n, 1, -1): # n-1

The whole thing the Python way for pss in range(n, 1, -1): # n-1 passes mx = max(a[0: pss]) loc = a. index(mx) a[loc], a[pss-1] = a[pss-1], a[loc]

2 -dimensional arrays n n Data sometimes has more structure to it than just

2 -dimensional arrays n n Data sometimes has more structure to it than just "a list" It has rows and columns You use two subscripts to locate an item The first subscript called “row”, second called “column”

2 -dimensional arrays n syntax n n n a = [[0]*5 for i in

2 -dimensional arrays n syntax n n n a = [[0]*5 for i in range(4)] # 5 columns, 4 rows Twenty elements, numbered from [0][0] to [4][3] a = [[0]*COLS for i in range(ROWS)] n Which has ROWS rows and COLS columns in each row (use of variables to make it easy to change the size of the array without having to edit every line of the program)

EXAMPLE -- Array for monthly high temperatures for all 50 states NUM_STATES = 50

EXAMPLE -- Array for monthly high temperatures for all 50 states NUM_STATES = 50 NUM_MONTHS = 12 state. Highs = [[0]*NUM_MONTHS for i in range(NUM_STATES)] [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10][11] [0] [1] row 2, [2] 66 64 72 78 85 90 99 105 98 90 88 80 col 7. might be. Arizona’s state. Highs[2][7] high for. August [48] [49]

Processing a 2 -d array by rows finding the total for the first row

Processing a 2 -d array by rows finding the total for the first row for i in range(NUM_MONTHS): total = total + a[0][i] finding the total for the second row for i in range(NUM_MONTHS): total = total + a[1][i]

Processing a 2 -d array by rows total for ALL elements by adding first

Processing a 2 -d array by rows total for ALL elements by adding first row, then second row, etc. for i in range(NUM_STATES): for j in range(NUM_MONTHS): total = total + a[i][j]

Processing a 2 -d array by columns total for ALL elements by adding first

Processing a 2 -d array by columns total for ALL elements by adding first column, second column, etc. for j in range(NUM_MONTHS): for i in range(NUM_STATES): total = total + a[i][j]

Finding the average high temperature for Arizona total = 0 for month in range(NUM_MONTHS):

Finding the average high temperature for Arizona total = 0 for month in range(NUM_MONTHS): total = total + state. Highs[2][month] average = round (total / NUM_MONTHS) ave rage 85

Passing an array as an argument n n n Arrays (lists) are passed by

Passing an array as an argument n n n Arrays (lists) are passed by reference = they CAN be changed permanently by the function Definition def fun 1 (arr): Call the function as x = fun 1 (myarr)

Arrays versus Files n n Arrays are usually smaller than files Arrays are faster

Arrays versus Files n n Arrays are usually smaller than files Arrays are faster than files Arrays are temporary, in RAM - files are permanent on secondary storage Arrays can do random or sequential, files we have seen are only sequential

Using Multidimensional Arrays Example of three-dimensional array

Using Multidimensional Arrays Example of three-dimensional array

NUM_DEPTS = 5 # mens, womens, childrens, electronics, furniture NUM_MONTHS = 12 NUM_STORES =

NUM_DEPTS = 5 # mens, womens, childrens, electronics, furniture NUM_MONTHS = 12 NUM_STORES = 3 # White Marsh, Owings Mills, Towson monthly. Sales = [[[0]*NUM_MONTHS for i in range(NUM_DEPTS)] for j in range(NUM_STORES)] 5 DEPTS rows S E R O s ST eet 3 sh monthly. Sales[3][7][0] sales for electronics in August at White Marsh 12 MONTHS columns

Example of filling a 3 -d array def main(): NUM_DEPTS = 5 # mens,

Example of filling a 3 -d array def main(): NUM_DEPTS = 5 # mens, womens, childrens, electronics, furniture NUM_MONTHS = 12 NUM_STORES = 3 # White Marsh, Owings Mills, Towson monthly. Sales = [[[0]*NUM_MONTHS for i in range(NUM_DEPTS)] for j in range(NUM_STORES)] store. Names = ["White Marsh", "Owings Mills", "Towson"] dept. Names = ["mens", "womens", "childrens", "electronics", "furniture"] for store in range(NUM_STORES): print (store. Names[store], end=" ") for dept in range(NUM_DEPTS): print (dept. Names[dept], end = " ") for month in range(NUM_MONTHS): print("for month number ", month+1) monthly. Sales[store][dept] [month] = float(input("Enter the sales ")) print() print (monthly. Sales)

Find the average of monthly_sales total = 0 for m in range(NUM_MONTHS): for d

Find the average of monthly_sales total = 0 for m in range(NUM_MONTHS): for d in range(NUM_DEPTS): for s in range(NUM_STORES): total += monthly. Sales [s][d][m] average = total / (NUM_MONTHS * NUM_DEPTS * NUM_STORES)

Problem: student data in a file n n The data is laid out as

Problem: student data in a file n n The data is laid out as Name, section, gpa n n John Smith, 15, 3. 2 Ralph Johnson, 12, 3. 9 Bob Brown, 9, 2. 5 Etc.

Read in the data inf = open(“students”, ”r”) studs = [] for line in

Read in the data inf = open(“students”, ”r”) studs = [] for line in inf: data = line. split(“, ”) studs. append(data) inf. close() #studs looks like [[“John Smith”, 15, 3. 2], #[“Ralph Johnson”, 12, 3. 9], [“Bob Brown”…]]

Find the student with highest GPA max = 0 for j in range(1, len(studs)):

Find the student with highest GPA max = 0 for j in range(1, len(studs)): if studs[max][2] < studs[j][2]: max = j #max is now location of highest gpa studs[max][0] is the name of the student studs[max][1] is the student’s section

Python Data Structures By Greg Felber

Python Data Structures By Greg Felber

Lists n n An ordered group of items Does not need to be the

Lists n n An ordered group of items Does not need to be the same type n n Could put numbers, strings or donkeys in the same list List notation n A = [1, ”This is a list”, c, Donkey(“kong”)]

Methods of Lists n List. append(x) n n List. extend(L) n n Extend the

Methods of Lists n List. append(x) n n List. extend(L) n n Extend the list by appending all in the given list L List. insert(I, x) n n adds an item to the end of the list Inserts an item at index I List. remove(x) n Removes the first item from the list whose value is x

Examples of other methods n a = [66. 25, 333, 1, 1234. 5] n

Examples of other methods n a = [66. 25, 333, 1, 1234. 5] n n //Returns the first index where the given value appears 1 //ouput a. reverse() n n n print a. count(333), a. count(66. 25), a. count('x') //calls method 210 //output a. index(333) n n //Defines List //Reverses order of list a //Prints list a [333, 1234. 5, 1, 333, -1, 66. 25] //Ouput a. sort() n n a //Prints list a [-1, 1, 66. 25, 333, 1234. 5] //Output

Using Lists as Stacks n n The last element added is the first element

Using Lists as Stacks n n The last element added is the first element retrieved To add an item to the stack, append() must be used n n stack = [3, 4, 5] stack. append(6) Stack is now [3, 4, 5, 6] To retrieve an item from the top of the stack, pop must be used n n n Stack. pop() 6 is output Stack is now [3, 4, 5] again

Using Lists as Queues n n First element added is the first element retrieved

Using Lists as Queues n n First element added is the first element retrieved To do this collections. deque must be implemented

List Programming Tools n Filter(function, sequence) n n Returns a sequence consisting of the

List Programming Tools n Filter(function, sequence) n n Returns a sequence consisting of the items from the sequence for which function(item) is true Computes primes up to 25

Map Function n Map(function, sequence) n Calls function(item) for each of the sequence’s items

Map Function n Map(function, sequence) n Calls function(item) for each of the sequence’s items n Computes the cube for the range of 1 to 11

Reduce Function n Reduce(function, sequence) n n Returns a single value constructed by calling

Reduce Function n Reduce(function, sequence) n n Returns a single value constructed by calling the binary function (function) Computes the sum of the numbers 1 to 10

The del statement n A specific index or range can be deleted

The del statement n A specific index or range can be deleted

Tuples n Tuple n n A number of values separated by commas Immutable n

Tuples n Tuple n n A number of values separated by commas Immutable n n n Cannot assign values to individual items of a tuple However tuples can contain mutable objects such as lists Single items must be defined using a comma n Singleton = ‘hello’,

Sets n n An unordered collection with no duplicate elements Basket = [‘apple’, ‘orange’,

Sets n n An unordered collection with no duplicate elements Basket = [‘apple’, ‘orange’, ‘apple’, ‘pear’] Fruit = set(basket) Fruit n Set([‘orange’, ‘apple’, ‘pear’])

Dictionaries n Indexed by keys n n This can be any immutable type (strings,

Dictionaries n Indexed by keys n n This can be any immutable type (strings, numbers…) Tuples can be used if they contain only immutable objects

Looping Techniques n Iteritems(): n for retrieving key and values through a dictionary

Looping Techniques n Iteritems(): n for retrieving key and values through a dictionary

Looping Techniques n Enumerate(): n for the position index and values in a sequence

Looping Techniques n Enumerate(): n for the position index and values in a sequence

n Zip(): n for looping over two or more sequences

n Zip(): n for looping over two or more sequences

Comparisons n n Operators “in” and “not in” can be used to see if

Comparisons n n Operators “in” and “not in” can be used to see if an item exists in a sequence Comparisons can be chained n a < b == c n This tests whether a is less than b and that b equals c

>> Classes

>> Classes

Object oriented programming Functions that can be performed on this data Data (specific to

Object oriented programming Functions that can be performed on this data Data (specific to each object) Apple tree ◦ Data ◦ Fruit Leaf Functions Pick_fruit() Pick_leaf() Can abstract into a Tree class ◦ Data Fruit Leaf ◦ Functions Pick_fruit() Pick_leaf() Instances: apple tree, maple tree, palm tree. .

Python is object oriented n n Lists, tuples, dictionaries, files-–were all objects of their

Python is object oriented n n Lists, tuples, dictionaries, files-–were all objects of their respective classes The functions we used on them were the member functions of those classes n list 1. append(‘a’)

Creating a class roster: course = "cis 530" def __init__(self, name, dept): self. student_name

Creating a class roster: course = "cis 530" def __init__(self, name, dept): self. student_name = name self. student_dept = dept Called when a object is ‘instantiated’ def print_details(self): print "Name: " + self. student_name print "Dept: " + self. student_dept print "Course: " + self. course Another member function Creating an instance student 1 = roster("annie", "cis") Calling methods of an student 1. print_details() object