Computer Science 111 Fundamentals of Programming I Sequences: Lists.

Slides:



Advertisements
Similar presentations
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Advertisements

CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Chapter 10 Introduction to Arrays
Fall 2008Programming Development Techniques 1 Topic 9 Symbol Manipulation Generating English Sentences Section This is an additional example to symbolic.
Fundamentals of Python: From First Programs Through Data Structures
Lecture 03 – Sequences of data.  At the end of this lecture, students should be able to:  Define and use functions  Import functions from modules 
2/28/2008. >>> Overview Arrays in Python – a.k.a. Lists Ranges are Lists Strings vs. Lists Tuples vs. Lists Map-Reduce Lambda Review: Printing to a file.
Computer Science 111 Fundamentals of Programming I Sequences: Strings.
Computer Science 112 Fundamentals of Programming II Recursive Processing of Languages.
Programming for Linguists An Introduction to Python 24/11/2011.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Lists in Python.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Lecture 06 – Reading and Writing Text Files.  At the end of this lecture, students should be able to:  Read text files  Write text files  Example.
CSE 143 Lecture 11 Maps Grammars slides created by Alyssa Harding
Topics: Sequence Sequences Index into a sequence [] notation Slicing and other operations.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
Fundamentals of Python: First Programs
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Artificial Intelligence: Natural Language
The man bites the dog man bites the dog bites the dog the dog dog Parse Tree NP A N the man bites the dog V N NP S VP A 1. Sentence  noun-phrase verb-phrase.
Syntax The Structure of a Language. Lexical Structure The structure of the tokens of a programming language The scanner takes a sequence of characters.
Computer Science 111 Fundamentals of Programming I Default and Optional Parameters Higher-Order Functions.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
Trinity College Dublin, The University of Dublin GE3M25: Computer Programming for Biologists Python, Class 4 Karsten Hokamp, PhD Genetics TCD, 01/12/2015.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Composing Music with Grammars. grammar the whole system and structure of a language or of languages in general, usually taken as consisting of syntax.
Computer Science 101 Python Lists. Literals, Assignment, Comparisons, Concatenation Similar to the behavior of strings so far a = [1, 2, 3] b = range(1,
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Chapter 5 Murach's JavaScript and jQuery, C1© 2012, Mike Murach & Associates, Inc.Slide 1.
Review: A Computational View Programming language common concepts: 1. sequence of instructions -> order of operations important 2. conditional structures.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
String and Lists Dr. José M. Reyes Álamo.
COMPSCI 107 Computer Science Fundamentals
Data types: Complex types (List)
Fundamentals of Programming II Recursive Processing of Languages
Fundamentals of Programming I A Sentence Generator
Containers and Lists CIS 40 – Introduction to Programming in Python
String Processing Upsorn Praphamontripong CS 1110
CSc 120 Introduction to Computer Programing II
Fundamentals of Programming I Design with Functions
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Perl Variables: Array Web Programming.
Computer Science 312 Haskell Lists 1.
Bryan Burlingame Halloween 2018
String and Lists Dr. José M. Reyes Álamo.
Chapter 5: Lists and Dictionaries
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Sequences Introduction to Lists List Slicing
Computer Science 111 Fundamentals of Programming I
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Basic String Operations String Slicing
Topics Sequences Introduction to Lists List Slicing
Topics Basic String Operations String Slicing
Text Files and Random Numbers
CSE 231 Lab 6.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Basic String Operations String Slicing
Introduction to Computer Science
Presentation transcript:

Computer Science 111 Fundamentals of Programming I Sequences: Lists

What Is a List? A list is a sequence of 0 or more data values (of any types) called elements The programmer can access or replace the element at any position in a list An element can be inserted at any position or removed from any position E1E2E

Real-World Examples A shopping list A schedule of athletic contests A team roster An algorithm (a list of instructions)

Literals, Assignment, Comparisons, Concatenation, for Loop Similar to the behavior of strings so far a = [1, 2, 3] b = list(range(1, 4)) # b now refers to [1, 2, 3] a == b # returns True a < [2, 3, 4] # returns True print(a + b) # displays [1, 2, 3, 1, 2, 3] print(len(a)) # displays 3 for element in [1, 2, 3]: print(element)

Indexing and Slicing Similar to the behavior of strings so far a = [1, 2, 3] print(a[2]) # Displays 3 print(a[len(a) - 1]) # Displays 3 print(a[-1]) # Displays 3 print(a[0:2]) # Displays [1, 2]

Replacing an Element To replace an element at a given position, use the subscript operator with the appropriate index Unlike strings, lists are mutable! [ ] = a = [1, 2, 3] a[1] = 5 # The list is now [1, 5, 3] print(a[1]) # Displays [1, 2, 3] 0 1 2

Replacing a Subsequence a = [1, 2, 3, 4] a[0:2] = [5, 6] print(a) # Displays [5, 6, 3, 4] 123 [1, 2, 3, 4]

Splitting split builds a list of tokens (words) from a string using the space or newline as the default separator s = 'Python is way cool!' lyst = s.split() print(lyst) # Displays ['Python', 'is', 'way', 'cool!'].split( )

Pattern Matching lyst = ['Ken', 100] [name, grade] = lyst print(name) # Displays Ken print(grade) # Displays 100

Application: Find the Highest Grade fileName = input('Enter the file name: ') inputFile = open(fileName, 'r') highestGrade = 0 topStudent = 'Nobody' for line in inputFile: [name, grade] = line.split() grade = int(grade) if grade > highestGrade: highestGrade = grade topStudent = name print(topStudent, 'has the highest grade', highestGrade) Assumes that each line of text in the file contains two words, a name and a grade (represented as an integer)

Joining join builds a string from a list of tokens (words) s = 'Python is way cool!' lyst = s.split() print(lyst) # Displays ['Python', 'is', 'way', 'cool!'] print(' '.join(lyst)) # Displays Python is way cool!.join( )

Application: Sentence Length Short sentences are an index of good writing style. Word processing programs allow you to do word counts. sentence = input('Enter a sentence: ') words = sentence.split() count = len(words) print('There are', count, 'words in your sentence.')

Application: Generate Sentences Given a vocabulary and grammar rules, one can generate some random and perhaps rather silly sentences Vocabulary - the set of words belonging to the parts of speech (nouns, verbs, articles, prepositions) Grammar - the set of rules for building phrases in a sentence (noun phrase, verb phrase, prepositional phrase)

The Structure of a Sentence sentence noun phrase verb phrase A sentence is a noun phrase followed by a verb phrase

The Structure of a Sentence sentence noun phrase verb phrase article noun A noun phrase is an article followed by a noun

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun the girl Pick actual words for those parts of speech at random

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase the girl A verb phrase is a verb followed by a noun phrase and a prepositional phrase

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase the girl hit Pick a verb at random

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun the girl hit Expand a noun phrase again

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun the girl hit the boy Pick an article and a noun at random

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun preposition noun phrase the girl hit the boy A prepositional phrase is a preposition followed by a noun phrase

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun preposition noun phrase the girl hit the boy with Pick a preposition at random

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun preposition noun phrase article noun the girl hit the boy with Expand another noun phrase

The Structure of a Sentence Similar to the behavior of strings so far sentence noun phrase verb phrase article noun verb noun phrase prepositional phrase article noun preposition noun phrase article noun the girl hit the boy with a bat More random words from the parts of speech

Representing the Vocabulary nouns = ['bat', 'boy', 'girl', 'dog', 'cat', 'chair', 'fence', 'table', 'computer', 'cake', 'field'] verbs = ['hit', 'threw', 'pushed', 'ate', 'dragged', 'jumped'] prepositions = ['with', 'to', 'from', 'on', 'below', 'above', 'beside'] articles = ['a', 'the'] Use a list of words for each part of speech (lexical category)

Picking a Word at Random nouns = ['bat', 'boy', 'girl', 'dog', 'cat', 'chair', 'fence', 'table', 'computer', 'cake', 'field'] verbs = ['hit', 'threw', 'pushed', 'ate', 'dragged', 'jumped'] prepositions = ['with', 'to', 'from', 'on', 'below', 'above', 'beside'] articles = ['a', 'the'] import random print(random.choice(verbs)) # Prints a randomly chosen verb The random module includes functions to select numbers, sequence elements, etc., at random

Grammar Rules sentence = nounphrase verbphrase nounphrase = article noun verbphrase = verb nounphrase prepositionalphrase preopositonalphrase = preposition nounphrase A sentence is a noun phrase followed by a verb phrase Etc., etc.

Define a Function for Each Rule # sentence = nounphrase verbphrase def sentence(): return nounphrase() + ' ' + verbphrase() Each function builds and returns a string that is an instance of the phrase Separate phrases and words with a space

Define a Function for Each Rule # sentence = nounphrase verbphrase def sentence(): return nounphrase() + verbphrase() # nounphrase = article noun def nounphrase(): return random.choice(articles) + ' ' + random.choice(nouns) When a part of speech is reached, select an instance at random from the relevant list

Call sentence() to Try It Out # sentence = nounphrase verbphrase def sentence(): return nounphrase() + verbphrase() # nounphrase = article noun def nounphrase(): return random.choice(articles) + ' ' + random.choice(nouns) … for x in range(10): print(sentence()) # Display 10 sentences You can also generate examples of the other phrases by calling their functions

Just the Tip of the Iceberg The list is a very powerful data structure There are many list processing methods A Python method is like a function, but uses a slightly different syntax

The append Method lyst = [1, 2, 3] lyst.append(4) print(lyst) # Displays [1, 2, 3, 4].append( ) # Puts the element at the end of the list # Actually modifies the list!!! Adds an element to the end of the list Syntax for calling the append method:

Functions vs Methods lyst = [1, 2, 3] lyst.append(4) # A method call print(len(lyst)) # Two function calls file = open('testfile.txt', 'r') # A function call wordList = file.read().split() # Two method calls. ( ) ( ) Syntax of method calls and function calls:

Some List Methods Example CallWhat It Does lyst.count(3) Returns the number of 3s in the list lyst.insert('dog', 2) Inserts 'dog' at position 2, after shifting the elements at positions 2 through N - 1 to the right lyst.pop(0) Removes the element at the first position and then shifts the remaining elements to the left by one position lyst.remove('dog') Removes the first instance of 'dog' in the list lyst.reverse() Reverses the elements lyst.sort() Sorts the elements in ascending order

For Wednesday Continue reading Chapter 5 on dictionaries