Lecture Data Collections. Richard E Sarkis CSC 161: The Art of Programming
|
|
- Marilynn Nichols
- 5 years ago
- Views:
Transcription
1 Lecture Data Collections Richard E Sarkis CSC 161: The Art of Programming
2 Class Administrivia
3 Agenda To understand the use of lists (arrays) to represent a collection of related data. To be familiar with the functions and methods available for manipulating Python lists. To be able to write programs that use lists to manage a collection of information.
4 Agenda To be able to write programs that use lists and classes to structure complex data. To understand the use of Python dictionaries for storing non-sequential collections.
5 Example: Simple Statistics
6 Example: Simple Statistics Many programs deal with large collections of similar information Words in a document Students in a course Data from an experiment Customers of a business Graphics objects drawn on the screen Cards in a deck
7 Example: Simple Statistics # average4.py # A program to average a set of numbers # Illustrates sentinel loop using empty string as sentinel def main(): sum = 0.0 count = 0 xstr = input("enter a number (<Enter> to quit) >> ") while xstr!= "": x = eval(xstr) sum = sum + x count = count + 1 xstr = input("enter a number (<Enter> to quit) >> ") print("\nthe average of the numbers is", sum / count) main()
8 Example: Simple Statistics This program allows the user to enter a sequence of numbers, but the program itself doesn't keep track of the numbers that were entered It only keeps a running total Suppose we want to extend the program to compute not only the mean, but also the median and standard deviation
9 Example: Simple Statistics The median is the data value that splits the data into equal-sized parts For the data 2, 4, 6, 9, 13, the median is 6, since there are two values greater than 6 and two values that are smaller One way to determine the median is to store all the numbers, sort them, and identify the middle value
10 Example: Simple Statistics The standard deviation is a measure of how spread out the data is relative to the mean If the data is tightly clustered around the mean, then the standard deviation is small If the data is more spread out, the standard deviation is larger The standard deviation is a yardstick to measure/ express how exceptional the data is
11 Example: Simple Statistics The standard deviation is N 1 s = N 1 i=1 (x i x) 2 Here x is the mean, x i represents the ith data value and n is the number of data values The expression (x i x) 2 is the square of the deviation of an individual item from the mean
12 Example: Simple Statistics The numerator is the sum of these squared deviations across all the data Suppose our data was 2, 4, 6, 9, and 13 The mean is 6.8 The numerator of the standard deviation is: (6.8 2) 2 +(6.8 4) 2 +(6.8 6) 2 +(6.8 9) 2 +(6.8 13) 2 = s = = 37.4 =6.11
13 Example: Simple Statistics As you can see, calculating the standard deviation not only requires the mean (which can't be calculated until all the data is entered), but also each individual data element We need some way to remember these values as they are entered
14 Applying Lists
15 Applying Lists We need a way to store and manipulate an entire collection of numbers We can't just use a bunch of variables, because we don't know many numbers there will be What do we need? Some way of combining an entire collection of values into one object
16 Applying Lists Python lists are ordered sequences of items. For instance, a sequence of n numbers might be called S: S = s0, s1, s2, s3,, sn-1 Specific values in the sequence can be referenced using subscripts By using numbers as subscripts, mathematicians can succinctly summarize computations over items in a sequence using subscript variables N i=1 s i
17 Applying Lists Suppose the sequence is stored in a variable s We could write a loop to calculate the sum of the items in the sequence like this: s = [2,4,6,9,13] _sum = 0 for i in range(len(s)): _sum = _sum + s[i] Almost all computer languages have a sequence structure like this, sometimes called an array.
18 Applying Lists A list or array is a sequence of items where the entire sequence is referred to by a single name (i.e. s) and individual items can be selected by indexing (i.e. s[i]) In other programming languages, arrays are generally a fixed size, meaning that when you create the array, you have to specify how many items it can hold Arrays are generally also homogeneous, meaning they can hold only one data type
19 Applying Lists Python lists are dynamic They can grow and shrink on demand. Python lists are also heterogeneous, a single list can hold arbitrary data types Python lists are mutable sequences of arbitrary objects
20 List Operations
21 List Operations Operator Meaning <seq> + <seq> Concatenation <seq> * <int-expr> Repetition <seq>[] Indexing len(<seq>) Length <seq>[:] Slicing for <var> in <seq>: Iteration <expr> in <seq> Membership (Boolean)
22 List Operations Except for the membership check, we've used these operations before on strings The membership operation can be used to see if a certain value appears anywhere in a sequence >>> lst = [1,2,3,4] >>> 3 in lst True
23 List Operations The summing example from earlier can be written like this: sum = 0 for x in s: sum = sum + x
24 List Operations Unlike strings, lists are mutable: >>> lst = [1,2,3,4] >>> lst[3] 4 >>> lst[3] = "Hello >>> lst [1, 2, 3, 'Hello'] >>> lst[2] = 7 >>> lst [1, 2, 7, 'Hello']
25 List Operations A list of identical items can be created using the repetition operator. This command produces a list containing 50 zeroes: zeroes = [0] * 50
26 List Operations Lists are often built up one piece at a time using append nums = [] x = eval(input('enter a number: ')) while x >= 0: nums.append(x) x = eval(input('enter a number: ')) nums is being used as an accumulator, starting out empty, and each time through the loop a new value is tacked on
27 List Operations Method <list>.append(x) <list>.sort() <list>.reverse() Meaning Add element x to end of list. Sort (order) the list. A comparison function may be passed as a parameter. 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) <list>.remove(x) <list>.pop(i) Returns the number of occurrences of x in list. Deletes the first occurrence of x in list. Deletes the ith element of the list and returns its value.
28 List Operations >>> lst = [3, 1, 4, 1, 5, 9] >>> lst.append(2) >>> lst [3, 1, 4, 1, 5, 9, 2] >>> lst.sort() >>> lst [1, 1, 2, 3, 4, 5, 9] >>> lst.reverse() >>> lst [9, 5, 4, 3, 2, 1, 1] >>> lst.index(4) 2 >>> lst.insert(4, "Hello") >>> lst [9, 5, 4, 3, 'Hello', 2, 1, 1] >>> lst.count(1) 2 >>> lst.remove(1) >>> lst [9, 5, 4, 3, 'Hello', 2, 1] >>> lst.pop(3) 3 >>> lst [9, 5, 4, 'Hello', 2, 1]
29 List Operations Most of these methods don't return a value! They change the contents of the list in some way Lists can grow by appending new items, and shrink when items are deleted Individual items or entire slices can be removed from a list using the del keyword
30 List Operations del isn't a list method, but a built-in operation that can be used on list items: >>> mylist=[34, 26, 0, 10] >>> del mylist[1] >>> mylist [34, 0, 10] >>> del mylist[1:3] >>> mylist [34]
31 List Operations Basic list principles A list is a sequence of items stored as a single object Items in a list can be accessed by indexing, and sublists can be accessed by slicing Lists are mutable individual items or entire slices can be replaced through assignment statements
32 List Operations Basic list principles Lists support a number of convenient and frequently used methods. Lists will grow and shrink as needed
33 Statistics with Lists
34 Statistics with Lists One way we can solve our statistics problem is to store the data in lists We could then write a series of functions that takes a list of numbers and calculates the mean, standard deviation, and median Let's rewrite our earlier program to use lists to find the mean
35 Statistics with Lists Let's write a function called getnumbers that gets numbers from the user We'll implement the sentinel loop to get the numbers An initially empty list is used as an accumulator to collect the numbers The list is returned once all values have been entered
36 Statistics with Lists Using this code, we can get a list of numbers from the user with a single line of code: data = getnumbers() def getnumbers(): nums = [] # start with an empty list # sentinel loop to get numbers xstr = input("enter a number (<Enter> to quit) >> ") while xstr!= "": x = eval(xstr) nums.append(x) # add this value to the list xstr = input("enter a number (<Enter> to quit) >> ") return nums
37 Statistics with Lists Now we need a function that will calculate the mean of the numbers in a list Input: a list of numbers Output: the mean of the input list def mean(nums): _sum = 0.0 for num in nums: _sum = _sum + num return _sum / len(nums)
38 Statistics with Lists The next function to tackle is the standard deviation In order to determine the standard deviation, we need to know the mean Should we recalculate the mean inside of stddev? Should the mean be passed as a parameter to stddev?
39 Statistics with Lists Recalculating the mean inside of stddev is inefficient if the data set is large Since our program is outputting both the mean and the standard deviation, let's compute the mean and pass it to stddev as a parameter
40 Statistics with Lists The summation from the formula is accomplished with a loop and accumulator sumdevsq stores the running sum of the squares of the deviations def stddev(nums, xbar): sumdevsq = 0.0 for num in nums: dev = xbar - num sumdevsq = sumdevsq + dev * dev return sqrt(sumdevsq/(len(nums)-1))
41 Statistics with Lists We don't have a formula to calculate the median. We'll need to come up with an algorithm to pick out the middle value 1. We need to arrange the numbers in ascending order. 2. The middle value in the list is the median. If the list has an even length, the median is the average of the middle two values
42 Statistics with Lists Pseudocode: sort the numbers into ascending order if the size of the data is odd: else: median = the middle value median = the average of the two middle values return median
43 Statistics with Lists def median(nums): nums.sort() size = len(nums) midpos = size // 2 if size % 2 == 0: median = (nums[midpos] + nums[midpos-1]) / 2 else: median = nums[midpos] return median
44 Statistics with Lists With these functions, the main program is pretty simple: def main(): print("this program computes mean, median print("and standard deviation.") data = getnumbers() xbar = mean(data) std = stddev(data, xbar) med = median(data) print("\nthe mean is", xbar) print("the standard deviation is", std) print("the median is", med
45 Statistics with Lists Statistical analysis routines might come in handy some time, so let's add the capability to use this code as a module by adding: if name == ' main ': main()
46 Lists of Objects
47 Lists of Objects All of the list examples we've looked at so far have involved simple data types like numbers and strings We can also use lists to store more complex data types, like our student information or and address book
48 Lists of Objects Our grade processing program read through a file of student grade information and then printed out information about the student with the highest GPA A common operation on data like this is to sort it, perhaps alphabetically, perhaps by credit-hours, or even by GPA
49 Lists of Objects Let's write a program that sorts students according to GPA using a Student class Pseudocode: Get the name of the input file from the user Read student information into a list Sort the list by GPA Get the name of the output file from the user Write the student info from the list into a file
50 Lists of Objects class Student: def init (self, name, hours, qpoints): self.name = name self.hours = float(hours) self.qpoints = float(qpoints) def getname(self): return self.name def gethours(self): return self.hours def getqpoints(self): return self.qpoints def gpa(self): return self.qpoints/self.hours def makestudent(infostr): # infostr is a tab-separated line: name hours qpoints # returns a corresponding Student object name, hours, qpoints = infostr.split("\t") return Student(name, hours, qpoints)
51 Lists of Objects A sample student data you can store in a file and use with the makestudent(infostr) function. Use tabs to separate each column of data. Adams, Henry Computewell, Susan DibbleBit, Denny Jones, Jim Smith, Frank
52 Lists of Objects Let's begin with the file processing.the following code reads through the data file and creates a list of students def readstudents(filename): infile = open(filename, 'r') students = [] for line in infile: students.append(makestudent(line)) infile.close() return students We're using the makestudent from the gpa program, so we'll need to remember to import it
53 Lists of Objects Using the functions readstudents and writestudents, we can convert our data file into a list of students and then write them back to a file. All we need to do now is sort the records by GPA In the statistics program, we used the sort method to sort a list of numbers How does Python sort lists of objects?
54 Lists of Objects To make sorting work with our objects, we need to tell sort how the objects should be compared Can supply a function to produce the key for an object using <list>.sort(key=<somefunc>) To sort by GPA, we need a function that takes a Student as parameter and returns the student's GPA
55 Lists of Objects To make sorting work with our objects, we need to tell sort how the objects should be compared def use_gpa(astudent): return astudent.gpa() We can now sort the data by calling sort with the key function as a keyword parameter To sort by GPA, we need a function that takes a Student as parameter and returns the student's GPA: data.sort(key=use_gpa)
56 Lists of Objects Notice that we didn't put ()'s after the function name: data.sort(key=use_gpa) This is because we don't want to call use_gpa, but rather, we want to send use_gpa to the sort method
57 Lists of Objects Actually, defining use_gpa was unnecessary. The gpa method in the Student class is a function that takes a student as a parameter (formally, self) and returns GPA Can use it: data.sort(key=student.gpa)
58 Lists of Objects # gpasort.py # A program to sort student information into GPA order. from gpa import Student, makestudent def readstudents(filename): infile = open(filename, 'r') students = [] for line in infile: students.append(makestudent(line)) infile.close() return students def main(): print ("This program sorts student grade information by GPA") filename = input("enter the name of the data file: ") data = readstudents(filename) data.sort(student.gpa) filename = input("enter a name for the output file: ") writestudents(data, filename) print("the data has been written to", filename) if name == ' main ': main() def writestudents(students, filename): outfile = open(filename, 'w') for s in students: print(s.getname(), s.gethours(), s.getqpoints(), sep="\t", file=outfile) outfile.close()
59 Tuples
60 Tuples A tuple is just another kind of sequence in Python A tuple looks like a list except that it is enclosed in round parentheses () instead of square brackets [ ] Tuples are like lists except that tuples are immutable the items can t be changed If the contents of a sequence won t be changed after it is created, using a tuple is more efficient than using a list
61 Tuples Tuples are used inside the Python interpreter to pass around information: Packing/Unpacking are fundamental features of Tuples that are used heavily in Python, behindthe-scenes
62 Dictionaries
63 Dictionaries A common data type used these days is a nonsequential collection called a Dictionary Lists are sequential, order is preserved Dictionaries, order is not-preserved
64 Dictionaries Rather than using a positional index, as in a list, it can be easier to refer to some data using a unique name. This is called a key-value pair We access the value (say, student information) associated with a particular key (student ID). It's a natural mode of organizing data for us
65 Dictionaries The concept of using key-value pairs in some collection data type, like a dictionary, is called mapping Python Dictionaries are mappings Similar structures in other languages: hashes, or associative arrays
66 Dictionaries There are two ways to start off a new, empty dictionary Use the Dictionary class constructor: d = dict() Use curly braces: d = {}
67 Dictionaries You can create a dictionary with pre-set values, too! passwd = {"guido":"superprogrammer", "turing":"genius", "bill":"monopoly"}
68 Dictionaries All key/value pairs in a dictionary assignment are made using a colon (":") character, and commas separate the key/value pairs themselves It's a lot easier to refer to a data value using a helpful key, rather than an abstract number as an index "Lookup data for 'guido' from the dictionary d" "Lookup data for index 5 from list lst"
69 Dictionaries That means, once you have a dictionary you can access any value by providing a key like this: <dictionary>[<key>] For example: >>> passwd["guido"] 'superprogrammer' >>> passwd["bill"] 'monopoly'
70 Dictionaries An important characteristic of dictionaries is that they are mutable Given a key, you can assign a new value through assignment: >>> passwd["bill"] = "bluescreen" >>> passwd {'turing': 'genius', 'bill': 'bluescreen', 'guido': 'superprogrammer'}
71 Dictionaries You can also extend a dictionary by adding new entries: >>> passwd['jobs'] = 'visionary' >>> passwd {'jobs': 'visionary', 'bill': 'monopoly', 'guido': 'superprogrammer', 'turing': 'genius'}
72 Dictionaries Notice, the order of the key/values in the dictionary differ from the order the key/values were entered Dictionaries rely on efficient mechanisms for lookup that may re-order the data pairs when you print out a dictionary This is intended, and not a problem if you use dictionaries for their intended use!
73 Dictionaries Some rules for dictionaries: The key for a dictionary item must be an immutable type! Strings (ah, that's why they're immutable!) Numbers (ints, floats) Tuples (Interesting ) The value for a dictionary item can be anything you want
74 Dictionaries A common pattern for working with dictionaries is to start with an empty collection and add key/value paris, one at a time What if we had a text file containing username and password pairs, one per line Can we read it in and add them to a dictionary?
75 Dictionaries You sure can, this is how: passwd = {} for line in open('passwords.txt','r'): user, _pass = line.split() passwd[user] = _pass
76 Dictionaries Dictionaries, being objects create from a class, have many built-in methods and attributes: Method <key> in <dict> <dict>.keys() <dict>.values() <dict>.items() <dict>.get(<key>, <default>) del <dict>[<key>] Meaning Returns true if dictionary contains the specified key, false if it doesn't Returns a sequence keys Returns a sequence of values Returns a sequence of tuples (key,value) representing If dictionary has the key key-value returns pairs its value; otherwise returns default Deletes the specified entry <dict>.clear() for <var> in <dict>: Deletes all entries Loop over the keys
77 Dictionaries >>> list(passwd.keys()) ['turing', 'bill', 'newuser', 'guido'] >>> list(passwd.values()) ['genius', 'bluescreen', 'ImANewbie', 'superprogrammer'] >>> list(passwd.items()) [('turing', 'genius'), ('bill', 'bluescreen'),\ ('newuser', 'ImANewbie'),('guido', 'superprogrammer')] >>> "bill" in passwd True >>> 'fred' in passwd False >>> passwd.get('bill','unknown') 'bluescreen' >>> passwd.get('john','unknown') 'unknown' >>> passwd.clear() >>> passwd {}
78 Example: Word Frequency
79 Example: Word Frequency Word frequency can be a simplistic measure of the style similarity between two documents Also useful for index and archiving for searching (Apple's Spotlight, search engines, etc) A word frequency program is a type of multiaccumulator pattern You need n unique variables to count n unique words in a document
80 Example: Word Frequency How do we count the frequency for each word that appears in a document? Assign variables for every unique word you think will come up? This won't be a scalable solution. You may have thousands of unique words! Lists might be usable for this, they are extendible, etc.
81 Example: Word Frequency Obviously, a dictionary is going to be our choice The keys of our dictionary holding these word frequencies will be the words themselves that we are counting Strings are immutable, remember The values of each key in this dictionary will be an integer, representing a frequency count
82 Example: Word Frequency Let's call our dictionary counts To update the count for a particular word, w, we do something like this: counts[w] = counts[w] + 1
83 Example: Word Frequency This says: "find the entry in our dictionary, using the value in w as our key" "Add 1 to this value" "Store this new value back into in our dictionary, using the value in w as our key"
84 Example: Word Frequency Does this always work? There is a complication, and edge case that needs to be handled
85 Example: Word Frequency What happens if we find a word that is not in our dictionary? We can't add 1 to a count value that doesn't exist yet We need to catch the condition where word w shows up for the first time
86 Example: Word Frequency Attempting to access a non- existent key produces a run-time KeyError To guard against this, we need a decision in our algorithm: if w is already in counts: add one to the count for w else: set count for w to 1
87 Example: Word Frequency When a word is first encountered, it will be given a value of 1, instead of attempting to add a value of 1 to a non-existent value: if w in counts: counts[w] = counts[w] + 1 else: counts[w] = 1
88 Example: Word Frequency Another approach is using dict's get method counts[w] = counts.get(w,0) + 1
89 Example: Word Frequency Or finally, you can try an exception handler: try: counts[w] = counts[w] + 1 except KeyError: counts[w] = 1
90 Example: Word Frequency We now have the heart of our program, the dictionary updating code Let's fill in the rest around this Split the text from the text files into a list of words Lowercase all words Eliminate punctuation Last, we print a report that summarizes our counts
91 Example: Word Frequency fname = input("file to analyze: ") # read file as one long string text = open(fname,"r").read() # convert all letters to lower case text = text.lower() # replace each punctuation character with a space for ch in!"#$%&()*+,-./:;<=>?@[\\]^_ { }~ : text = text.replace(ch, " ") # split string at whitespace to form a list of words words = text.split() # Loop through the words to build the counts dictionary counts = {} for w in words: counts[w] = counts.get(w,0) + 1
92 Example: Word Frequency Our last step is to print out a report summarizing the counts of our counts dictionary One approach is to print out a list of words and their associated counts, alphabetically: # get list of words that appear in document uniquewords = list(counts.keys()) # put list of words in alphabetical order uniquewords.sort() # print words and associated counts for w in uniquewords: print(w, counts[w])
93 Example: Word Frequency If this document is very large, with n words being in the thousands, it becomes inconvenient to list all the word frequencies What if we take the the frequencies of m words, where m < n? We'll use tuples to help us solve this issue!
94 Example: Word Frequency Let's get a list of key/value pairs: items = list(counts.items()) We might see a list of tuples, like this, in items: [('foo',5), ('bar',7), ('spam',376),...]) Simply calling items.sort() won't work, as it will sort them alphabetically, which we do not want
95 Example: Word Frequency We use a trick where we can pass a function as an argument to another function! Define a new function: Then, call: def byfreq(pair): return pair[1] items.sort(key=byfreq)
96 Example: Word Frequency Almost done, but what happens when we sort by frequency but we have words with the same frequency? We need to sort our list twice! Sort first, alphabetically Next, sort by frequency
97 Example: Word Frequency The list sort() method is said to be stable If all words are in alphabetical order before sorting them by frequency, then words having the same frequency will still be in alphabetical order between themselves
98 Example: Word Frequency Here is our two-step sort, where we perform a reverse sort on frequencies so the highest frequencies are first in the list: items.sort() # orders pairs alphabetically items.sort(key=byfreq, reverse=true) # orders by frequency
99 Example: Word Frequency We print our report of word frequencies to the screen, and we are finished
100 # wordfreq.py def byfreq(pair): return pair[1] def main(): print("this program analyzes word frequency in a file") print("and prints a report on the n most frequent words.\n") # get the sequence of words from the file fname = input("file to analyze: ") text = open(fname,'r').read() text = text.lower() for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{ }~': text = text.replace(ch, ' ') words = text.split() # construct a dictionary of word counts counts = {} for w in words: counts[w] = counts.get(w,0) + 1 # output analysis of n most frequent words. n = eval(input("output analysis of how many words? ")) items = list(counts.items()) items.sort() items.sort(key=byfreq, reverse=true) for i in range(n): word, count = items[i] print("{0:<15}{1:>5}".format(word, count)) if name == ' main ': main()
101 Questions?
Introduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 11 Part 1 The Department of Computer Science Objectives Chapter 11 Data Collections To understand the use of lists (arrays)
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 11 Part 1 Instructor: Long Ma The Department of Computer Science Chapter 11 Data Collections Objectives: To understand the
More informationOutline: Data collections (Ch11)
Data collections Michael Mandel Lecture 9 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture09final.ipynb
More informationList OperaYons. Python Programming, 2/e 2
People s Daily With today s announcement, Kim joins the ranks of The Onion s prior Sexiest Man Alive winners, including: 2011: Bashar al- Assad 2010: Bernie Madoff 2009: Charles and David Koch (co- winners)
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Review Chap.11-12 Instructor: Long Ma The Department of Computer Science Chapter 11 Data Collections understand the use of lists
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 10 Part 3 & Chapter 11 Part 1 The Department of Computer Science Widgets One very common use of objects is in the design
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 10 Part 1 Instructor: Long Ma The Department of Computer Science Top-Down Design 2 In top-down design, a complex problem
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 8 Part 1 The Department of Computer Science Chapter 8 Loop Structures and Booleans 2 Objectives To understand the concepts
More informationLecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming
Lecture Loops && Booleans Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda (In-)definite loops (for/while) Patterns: interactive loop and sentinel loop Solve problems using (possibly
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Objectives æ To understand the programming pattern simple decision and its implementation
More informationCMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries
CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries Assignment: Lab 12 Tuples and Dictionaries Due Date: During discussion, November 30 th through December 3 rd Value: 1% of final grade Part 1: Data Types
More informationAll programs can be represented in terms of sequence, selection and iteration.
Python Lesson 3 Lists, for loops and while loops Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 28 Nicky Hughes All programs can be represented in terms of sequence, selection and iteration. 1 Computational
More informationLists, loops and decisions
Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 10 Part 2 The Department of Computer Science Cannonball Program Specification Let s try to write a program that simulates
More informationLoop structures and booleans
Loop structures and booleans Michael Mandel Lecture 7 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture07final.ipynb
More informationCollections. Lists, Tuples, Sets, Dictionaries
Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again
More informationData Structures. Lists, Tuples, Sets, Dictionaries
Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,
More informationTopic 7: Lists, Dictionaries and Strings
Topic 7: Lists, Dictionaries and Strings The human animal differs from the lesser primates in his passion for lists of Ten Best H. Allen Smith 1 Textbook Strongly Recommended Exercises The Python Workbook:
More informationPython. Olmo S. Zavala R. Python Data Structures. Lists Tuples Dictionaries. Center of Atmospheric Sciences, UNAM. August 24, 2016
Center of Atmospheric Sciences, UNAM August 24, 2016 are the most versatile datatype available in. It can be seen as a container of other types of variables. are identified with square brackets and its
More informationIntroduction to Python
Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions
More informationLecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming
Lecture Writing Programs Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To be able to understand and write Python statements to output information to the screen To assign values
More informationIntro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming
Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals
More informationIntro. Scheme Basics. scm> 5 5. scm>
Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if
More informationAdmin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return
Recursion CS 1 Admin How's the project coming? After these slides, read chapter 13 in your book Yes that is out of order, but we can read it stand alone Quizzes will return Tuesday Nov 29 th see calendar
More informationDictionaries in Python
Dictionaries in Python Zelle, 11.6 Learning Python, 8.3, 8.4 1 2 Dictionary Basics A dictionary can be created by listing key-value pairs inside curly braces Keys and values are joined with : Main function:
More informationCS2304: Python for Java Programmers. CS2304: Sequences and Collections
CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for
More informationThe Big Python Guide
The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String
More informationChapter 8 SETS AND DICTIONARIES
Chapter 8 SETS AND DICTIONARIES Chapter Goals To build and use a set container To learn common set operations for processing data To build and use a dictionary container To work with a dictionary for table
More informationCME 193: Introduction to Scientific Python Lecture 4: Strings and File I/O
CME 193: Introduction to Scientific Python Lecture 4: Strings and File I/O Nolan Skochdopole stanford.edu/class/cme193 4: Strings and File I/O 4-1 Contents Strings File I/O Classes Exercises 4: Strings
More informationPython Intro GIS Week 1. Jake K. Carr
GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes
More informationLecture. Algorithm Design and Recursion. Richard E Sarkis CSC 161: The Art of Programming
Lecture Algorithm Design and Recursion Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Objectives To understand the basic techniques for analyzing the efficiency of algorithms To know
More informationDefinition: A data structure is a way of organizing data in a computer so that it can be used efficiently.
The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without
More informationLISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University
LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python
More information6.001 Notes: Section 8.1
6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything
More informationA lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.
Handout 2 Functions, Lists, For Loops and Tuples [ ] Functions -- parameters/arguments, "calling" functions, return values, etc. Please make sure you understand this example: def square(x): return x *
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationStatistics Case Study 2000 M. J. Clancy and M. C. Linn
Statistics Case Study 2000 M. J. Clancy and M. C. Linn Problem Write and test functions to compute the following statistics for a nonempty list of numeric values: The mean, or average value, is computed
More information\n is used in a string to indicate the newline character. An expression produces data. The simplest expression
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationAlgorithm Design and Recursion. Search and Sort Algorithms
Algorithm Design and Recursion Search and Sort Algorithms Objectives To understand the basic techniques for analyzing the efficiency of algorithms. To know what searching is and understand the algorithms
More informationMITOCW watch?v=rvrkt-jxvko
MITOCW watch?v=rvrkt-jxvko The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To
More informationEE 355 Unit 17. Python. Mark Redekopp
1 EE 355 Unit 17 Python Mark Redekopp 2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 3 Python in Context Interpreted,
More informationFor strings (and tuples, when we get to them), its easiest to think of them like primitives directly stored in the variable table.
Page 1 6.189 Notes Session 8 Day 6: Immutable Objects Earlier, we made a big deal about the fact that lists are mutable. The reason this is important is because certain objects are immutable once created,
More informationOOP and Scripting in Python Advanced Features
OOP and Scripting in Python Advanced Features Giuliano Armano Emanuele Tamponi Advanced Features Structure of a Python Script More on Defining Functions Default Argument Values Keyword Arguments Arbitrary
More informationThe Practice of Computing Using PYTHON
The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures
More informationMUTABLE LISTS AND DICTIONARIES 4
MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable
More informationLECTURE 3 Python Basics Part 2
LECTURE 3 Python Basics Part 2 FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for the use of a special kind of function, a lambda function.
More informationCOLLEGE OF ENGINEERING, NASHIK-4
Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK-4 DEPARTMENT OF COMPUTER ENGINEERING Important PYTHON Questions 1. What is Python? Python is a high-level, interpreted, interactive and object-oriented
More informationVariable and Data Type 2
The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 3 Variable and Data Type 2 Eng. Ibraheem Lubbad March 2, 2017 Python Lists: Lists
More informationCircuitPython 101: Working with Lists, Iterators and Generators
CircuitPython 101: Working with Lists, Iterators and Generators Created by Dave Astels Last updated on 2018-11-01 12:06:56 PM UTC Guide Contents Guide Contents Overview List Functions Slicing Filtering
More informationOverview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017
Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable
More informationCSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray
CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray 01-c: Python review 2 python review: lists strings 3 Strings lists names = "John, Paul, Megan, Bill, Mary" names
More informationOutline: Defining objects (Ch10)
Defining objects Michael Mandel Lecture 10 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture10final.ipynb
More informationPython Programming: An Introduction To Computer Science
Python Programming: An Introduction To Computer Science Chapter 8 Loop Structures and Booleans Python Programming, 3/e 1 Objectives To understand the concepts of definite and indefinite loops as they are
More informationCMSC 201 Spring 2018
CMSC 201 Spring 2018 Name Midterm Review Worksheet This worksheet is NOT guaranteed to cover every topic you might see on the exam. It is provided to you as a courtesy, as additional practice problems
More informationPython Lists and for Loops. Learning Outcomes. What s a List 9/19/2012
Python Lists and for Loops CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17 1 Learning Outcomes Be aware that multiple items can be stored in a list. Become
More informationWorksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords
Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long
More informationProgram Planning, Data Comparisons, Strings
Program Planning, Data Comparisons, Strings Program Planning Data Comparisons Strings Reading for this class: Dawson, Chapter 3 (p. 80 to end) and 4 Program Planning When you write your first programs,
More informationPython: common syntax
Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable
More informationPython - Variable Types. John R. Woodward
Python - Variable Types John R. Woodward Variables 1. Variables are nothing but named reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.
More information6. Data Types and Dynamic Typing (Cont.)
6. Data Types and Dynamic Typing (Cont.) 6.5 Strings Strings can be delimited by a pair of single quotes ('...'), double quotes ("..."), triple single quotes ('''...'''), or triple double quotes ("""...""").
More informationECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction
ECE 364 Software Engineering Tools Lab Lecture 3 Python: Introduction 1 Introduction to Python Common Data Types If Statements For and While Loops Basic I/O Lecture Summary 2 What is Python? Python is
More informationIntroduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH
Introduction to Python Ph.D. Scien5fic Compu5ng Consultant PACE GATECH Things Covered What is Python? How to access Python environment? Fundamental elements in Python Variables (assignment, comparison,
More informationCIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani
CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 1 / 34
More informationIntroduction to Python Code Quality
Introduction to Python Code Quality Clarity and readability are important (easter egg: type import this at the Python prompt), as well as extensibility, meaning code that can be easily enhanced and extended.
More informationData Structures (list, dictionary, tuples, sets, strings)
Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 7 Part 2 The Department of Computer Science Quick review one-way or simple decision if : two-way decision
More informationThere are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:
Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited
More informationAI Programming CS S-02 Python
AI Programming CS662-2013S-02 Python David Galles Department of Computer Science University of San Francisco 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use
More informationPart I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming
2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float
More informationPython I. Some material adapted from Upenn cmpe391 slides and other sources
Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics
More informationData type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.
NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike
More informationCMSC201 Computer Science I for Majors
CMSC201 Computer Science I for Majors Lecture 08 Lists Constants Last Class We Covered More on while loops Sentinel loops Boolean flags 2 Any Questions from Last Time? 3 Today s Objectives To learn about
More informationLecture. Defining Functions. Richard E Sarkis CSC 161: The Art of Programming
Lecture Defining Functions Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To understand why programmers divide program code up into sets of cooperating functions To be able
More informationOutline: Search and Recursion (Ch13)
Search and Recursion Michael Mandel Lecture 12 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture12final.ipynb
More informationChapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values.
Chapter 8 Dictionaries Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values. Creating a Dictionary To create a dictionary, you need
More informationWorking with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.
Working with Strings Husni "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc. Sequence of characters We've talked about strings being a sequence of characters.
More informationmith College Computer Science Week 13 CSC111 Fall 2015 (Lab 12, Homework 12) Dominique Thiébaut
mith College Computer Science Week 13 CSC111 Fall 2015 (Lab 12, Homework 12) Dominique Thiébaut dthiebaut@smith.edu This Week: Two Concepts Lists of Lists Class Inheritance Lists of Lists (Chapter 11 Designing
More informationCSC 326H1F, Fall Programming Languages. What languages do you know? Instructor: Ali Juma. A survey of counted loops: FORTRAN
What languages do you know? CSC 326H1F, Programming Languages The usual suspects: C, C++, Java fine languages nearly the same Perhaps you've also learned some others? assembler Basic, Visual Basic, Turing,
More informationENGR 102 Engineering Lab I - Computation
ENGR 102 Engineering Lab I - Computation Week 07: Arrays and Lists of Data Introduction to Arrays In last week s lecture, 1 we were introduced to the mathematical concept of an array through the equation
More informationCS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like
CS662-2013S-02 Python 1 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use examples involving spam, parrots (deceased), silly walks, and the like Interpreted language
More informationAt full speed with Python
At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3
More information6.001 Notes: Section 15.1
6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define
More informationPython Review IPRE
Python Review 2 Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries
More informationPython allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:
1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,
More informationComputer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python
Day 3: Collections Suggested reading: Learning Python (3rd Ed.) Chapter 8: Lists and Dictionaries Chapter 9: Tuples, Files, and Everything Else Chapter 13: while and for Loops 1 Turn In Homework 2 Homework
More informationA new data type: Lists. March 5, 2018 Sprenkle - CSCI Ø How can we convert from the numerical representa9on to the character?
Objec9ves A new data type: Lists March 5, 2018 Sprenkle - CSCI111 1 Review How can we convert between characters and their numerical representa9on? Ø How can we convert from the numerical representa9on
More informationPython Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]
Python Lists: Lists are Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). All the items belonging to a list can be of different data type.
More informationTUPLES AND RECURSIVE LISTS 5
TUPLES AND RECURSIVE LISTS 5 COMPUTER SCIENCE 61A July 3, 2012 1 Sequences From the Pig project, we discovered the utility of having structures that contain multiple values. Today, we are going to cover
More informationCMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want
More information1 of 5 5/11/2006 12:10 AM CS 61A Spring 2006 Midterm 2 solutions 1. Box and pointer. Note: Please draw actual boxes, as in the book and the lectures, not XX and X/ as in these ASCII-art solutions. Also,
More informationHere is a simple dictionary in Python. Let s store the telephone dialing codes for a few countries.
1 DICTIONARIES, TUPLES and SETS Python is renowned for its data types that allow us to store a collection of data. The most popular of these is the list, which you have already seen. A list is a collection
More informationSequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python
Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted
More informationSTATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration
STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the
More informationMITOCW watch?v=0jljzrnhwoi
MITOCW watch?v=0jljzrnhwoi The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationAdvanced Python. Executive Summary, Session 1
Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.
More information(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.
Basics of Python - 2 by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 54 Sunday 16 February 2014 05:30 PM Our First Program - Rewritten! Let us introduce the following
More informationUnit E Step-by-Step: Programming with Python
Unit E Step-by-Step: Programming with Python Computer Concepts 2016 ENHANCED EDITION 1 Unit Contents Section A: Hello World! Python Style Section B: The Wacky Word Game Section C: Build Your Own Calculator
More informationWeek - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02)
Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 04 Lecture - 01 Merge Sort (Refer
More informationCompsci 101 Fall 2015 Exam 1 Rubric. Problem 1 (24 points)
Compsci 101 Fall 2015 Exam 1 Rubric Problem 1 (24 points) Each answer is one point each. Spelling of int, integer doesn't matter. Similarly string, str doesn't matter. For the value column all answers
More information