James Tam Advanced Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types.

Slides:



Advertisements
Similar presentations
Container Types in Python
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.
Java Programming Strings Chapter 7.
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.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
James Tam Advanced Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types.
Lists Introduction to Computing Science and Programming I.
James Tam Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types that are.
James Tam Classes and Objects You will learn how to define new types of variables.
James Tam Lists In this section of notes you will be introduced to new type of variable that consists of other types.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Lists in Python.
Composite Types You will learn how to create new variables that are collections of other entities.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 8 More on Strings and Special Methods 1.
James Tam Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types that are.
Python for Informatics: Exploring Information
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
James Tam Classes and Objects You will learn how to define new types of variables.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
CS105 STRING LIST TUPLE DICTIONARY. Characteristics of Sequence What is sequence data type? It stores several objects Each object has an order Each object.
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Data Collections CS 127. Lists Lists are ordered sequences of items All programming languages provide a sequence structure similar to a Python list; in.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
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.
INLS 560 – S TRINGS Instructor: Jason Carter. T YPES int list string.
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.
String and Lists Dr. José M. Reyes Álamo.
Containers and Lists CIS 40 – Introduction to Programming in Python
String Processing Upsorn Praphamontripong CS 1110
CMPT 120 Topic: Python strings.
Strings Part 1 Taken from notes by Dr. Neil Moore
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Introduction to Strings
Introduction to Strings
Bryan Burlingame Halloween 2018
Chapter 8 More on Strings and Special Methods
CS190/295 Programming in Python for Life Sciences: Lecture 6
Chapter 8 More on Strings and Special Methods
Python - Strings.
8 – Lists and tuples John R. Woodward.
Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types that are used for.
Chapter 8 More on Strings and Special Methods
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
Lists Part 1 Taken from notes by Dr. Neil Moore
Basic String Operations
Introduction to Strings
CS 1111 Introduction to Programming Spring 2019
CISC101 Reminders Assignment 2 due today.
Topics Basic String Operations String Slicing
Introduction to Computer Science
Topics Sequences Introduction to Lists List Slicing
Introduction to Strings
Topics Basic String Operations String Slicing
Introduction to Strings
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Topics Basic String Operations String Slicing
Presentation transcript:

James Tam Advanced Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types that are used for different scenarios.

James Tam Composite Variables To Be Covered Strings Lists (characteristics that differ from the array type from other programming languages). Tuples Dictionaries Classes

James Tam Small Example Programs Using Strings They can be found in UNIX in the directory: /home/231/examples/composites -string1.py (passing a whole string to a function) -string2.py (indexing the parts of a string) -string3.py (demonstrating the immutability of strings) -string4.py (string slicing) -string5.py (strings as sets, test for inclusion using ‘in’) -string6.py (strings that are repetitive sequence) -string7.py (using string functions: converting string input to numerical) -string8.py (using string functions that return modified versions of a string) -string9.py (string search functions)

James Tam String Strings are just a series of characters (e.g., alpha, numeric, punctuation etc.) Similar to lists a string can be treated as one entity. def fun (aString): print aString # MAIN aString = “Goodbye cruel world!” fun (aString) Or much like a list the individual elements (characters) can be accessed via an index. # MAIN aString = "hello" print aString[1], print aString[4],

James Tam Strings Are Immutable Even though it may look a string can change they actually cannot be edited. # MAIN aString = "good-bye" print aString aString = "hello" print aString aString[0] = "G“# Error

James Tam String Slicing Slicing a string will return a portion of a string (In other programming languages this is described as getting a ‘sub-string’ of a string). Format: string_name [start_index : end_index] Example: aString = "abcdefghij" print aString temp = aString [2:5] print temp temp = aString [:5] print temp temp = aString [7:] print temp

James Tam Strings Can Be Conceptualized As Sets The ‘ in ’ and ‘ not in ’ operations can be performed on a string. Branching passwords = "aaa abc password xxx" password = raw_input ("Password: ") if password in passwords: print "You entered an existing password, enter a new one“ Looping (iterating through the elements) sentence = "hihi there!" for temp in sentence: sys.stdout.write(temp)

James Tam Repetitive Strings A string with a number of repeated characters can be initialized in a number of ways. aString = “xxxxxxxx” aString = “hi!” * 5

James Tam String Testing Functions 1 These functions test a string to see if a given condition has been met and return either “ True ” or “ False ” Format: string_name.function_name () 1 These functions will return false if the string is empty (less than one character).

James Tam String Testing Functions (2) FunctionDescription isalpha () Only true if the string consists only of alphabetic characters. isdigit () Only returns true if the string consists only of digits. isalnum () Only returns true if the string is composed only of alphabetic characters or numeric digits. islower () Only returns true if the alphabetic characters in the string are all lower case. isspace () Only returns true if string consists only of whitespace characters ( “ “, “\n”, “\t”) isupper () Only returns true if the alphabetic characters in the string are all upper case.

James Tam Applying A String Testing Function # MAIN ok = False while (ok == False): temp = raw_input ("Enter numbers not characters: ") ok = temp.isdigit() if (ok == False): print temp, "is not a number" else: print "done" num = int (temp) num = num + num print num

James Tam Functions That Modify Strings These functions return a modified version of an existing string (leaves the original string intact). FunctionDescription lower () Returns a copy of the string with all the alpha characters as lower case (non-alpha characters are unaffected). upper () Returns a copy of the string with all the alpha characters as upper case (non-alpha characters are unaffected). strip () Returns a copy of the string with all leading and trailing whitespace characters removed. lstrip () Returns a copy of the string with all leading (left) whitespace characters removed. rstrip () Returns a copy of the string with all trailing (right) whitespace characters removed. lstrip (char) Returns a copy of the string with all leading instances of the character parameter removed. rstrip (char) Returns a copy of the string with all trailing instances of the character parameter removed.

James Tam Example Uses Of Functions That Modify Strings aString = "talk1! AbouT" print aString aString = aString.upper () print aString aString = "xxhello there" print aString aString = aString.lstrip ('x') print aString aString = "xxhellx thxrx" aString = aString.lstrip ('x') print aString

James Tam Functions To Search Strings FunctionDescription endswith (substring) A substring is the parameter and the function returns true only if the string ends with the substring. startswith (substring) A substring is the parameter and the function returns true only if the string starts with the substring. find (substring) A substring is the parameter and the function returns the lowest index in the string where the substring is found (or -1 if the substring was not found). replace (oldstring, newstring) The function returns a copy of the string with all instances of ‘ oldstring ’ replace by ‘ newstring ’

James Tam Examples Of Functions To Search Strings temp = raw_input ("Enter a sentence: ") if not ((temp.endswith('.')) or (temp.endswith('!')) or (temp.endswith ('?'))): print "Not a sentence" temp = "XXabcXabcabc" index = temp.find("abc") print index temp = temp.replace("abc", "Abc") print temp

James Tam The List Revisited So far the list that you have seen all contain elements that store the same type of information (homogenous). Arrays in most programming languages must be homogenous. Lists in Python do not have the requirement where the elements are all of the same type. -They can be homogenous as they were in the previous examples. -But lists can also be non-homogenous.

James Tam The List Revisited (2) Why is their a need for non-homogenous composite type? What if different types of information needs to be tracked as a composite type? Example, storing information about a client: First name Last name Phone number Address Postal code address Total purchases made …series of characters …numerical or character …series of characters …numerical or character

James Tam The List Revisited (3) If just a few clients need to be tracked then a simple list can be employed: firstClient = ["James", "Tam", "(403) ", "ICT 707, 2500 University Dr NW", "T2N-1N4", 0]

James Tam The List Revisited (4) (Or as a small example) def display (firstClient): print "DISPLAYING CLIENT INFORMATION" print " " for i in range (0, 7, 1): print firstClient [i] # MAIN firstClient = ["James", "Tam", "(403) ", "ICT 707, 2500 University Dr NW", "T2N-1N4", 0] display (firstClient)

James Tam The List Revisited (5) If only a few instances of the composite type (e.g., “Clients”) need to be created then multiple single lists can be employed. firstClient = ["James", "Tam", "(403) ", "ICT 707, 2500 University Dr NW", "T2N-1N4", 0] secondClient = ["Peter", "Griffin", "(708) ", "725 Spoon Street", "NA", 100]

James Tam The List Revisited (6) If a large number of composite types need to be tracked (e.g., many clients) then you can employ lists of lists. (This means that each list element consists of another list).

James Tam Example: List Of Lists The full example can be found in UNIX under: /home/231/examples/composites/list_of_lists.py MAX = 4 def initialize (myClients): for i in range (0, MAX, 1): temp = [(i+1), "first name", "last name", "(111) ", "address", "X0X-0X0", 0] myClients.append(temp)

James Tam Example: Lists Of Lists (2) def display (myClients): for i in range (0, MAX, 1): print myClients[i] # MAIN myClients = [] initialize (myClients) display(myClients)

James Tam Small Example Programs Using Lists They can be found in UNIX in the directory: /home/231/examples/composites -list1.py (concatenation and repetition) -list2.py (membership)

James Tam Some List Operations Operation nameOperatorDescription Indexing [] Access a list element Concatenation + Combine lists Repetition * Concatenate a repeated number of times Membership In Query whether an item is a member of a list Membership not in Query whether an item is not a member of a list Length len Return the number of items in a list Slicing [ : ] Extract a part of a list

James Tam Examples: Concatenation And Repetition list1 = [1, 2.0, "foo"] list2 = [[1,2,3], "salam"] print list1 print list2 list1 = list1 * 2 print list1 list3 = list1 + list2 print list3

James Tam Examples: Membership print "Example 1: " recall_list = ["vpn123", "ncc1946", "gst7"] item = raw_input ("Product code: ") if item in recall_list: print "Your product was on the recall list, take it back" else: print "You're safe" print print "Example 2:" days = ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"] for temp in days: print temp

James Tam Some Useful List Operations OperationFormatDescription Append list_name.append (item) Adds a new item to the end of the list Insert list_name.insert (i, item) Inserts a new item at index ‘i’ Sort list_name.sort () Sorts from smallest to largest Reverse list_name.reverse () Reverses the current order of the list Count list_name.count (item) Counts and returns the number of occurrences of the item

James Tam Drawback Of Using Lists Lists (and lists of lists) can be used to track relatively simple information e.g., grades, text-based virtual worlds. It is less effective at storing more complex information (e.g., client list). Some problems: -Which field contains what type of information? This isn’t immediately clear from looking at the program statements. -Is there any way to specify rules about the type of information to be stored in a field e.g., a data entry error could allow alphabetic information to be entered in the phone number field.

James Tam Classes Can be used define a generic template for a new non- homogeneous composite type. It can label and define more complex entities than a list. This template defines what an instance or example of this new composite type would consist of but it doesn’t create an instance.

James Tam Defining A Class Format: class : name of first field = name of second field = Example: class Client: firstName = "default" lastName = "default" phone = "(123) " address = "default address" postalCode = "XXX-XXX" = purchases = 0 Describes what information that would be tracked by a “Client” but doesn’t actually create a client in memory

James Tam Creating An Instance Of A Class Format: = () Example: firstClient = Client ()

James Tam Defining A Class Vs. Creating An Instance Of That Class Defining a class -A template that describes that class: how many fields, what type of information will be stored by each field, what default information will be stored in a field. Creating a class -Instances of that class (instantiations) which can take on different forms.

James Tam Accessing And Changing The Fields Format:. Example: firstClient.firstName = "James"

James Tam The Client List Example Implemented Using Classes The full version can be found in UNIX under /home/231/examples/composites/client.py class Client: firstName = "default" lastName = "default" phone = "(123) " address = "default address" postalCode = "XXX-XXX" = purchases = 0

James Tam The Client List Example Implemented Using Classes (2) firstClient = Client () firstClient.firstName = "James" firstClient.lastName = "Tam" firstClient. = print firstClient.firstName print firstClient.lastName print firstClient.phone print firstClient.address print firstClient.postalCode print firstClient. print firstClient.purchases

James Tam What Is The Benefit Of Defining A Class It allows new types of variables to be declared. The new type can model information about most any arbitrary entity: -Car -Movie -Your pet -A biological entity in a simulation -A ‘critter’ a video game -An ‘object’ in a video game -Etc.

James Tam What Is The Benefit Of Defining A Class (2) Unlike creating a composite type by using a list a predetermined number of fields can be specified and those fields can be named. class Client: firstName = "default" lastName = "default" phone = "(123) " address = "default address" postalCode = "XXX-XXX" = purchases = 0 firstClient = Client () print firstClient.middleName

James Tam What Is The Benefit Of Defining A Class (2) Unlike creating a composite type by using a list a predetermined number of fields can be specified and those fields can be named. class Client: firstName = "default" lastName = "default" phone = "(123) " address = "default address" postalCode = "XXX-XXX" = purchases = 0 firstClient = Client () print firstClient.middleName There is no field by this name

James Tam Tuples Much like a list, a tuple is a composite type whose elements can consist of any other type. Tuples support many of the same operators as lists such as indexing. However tuples are immutable. Tuples are used to store data that should not change.

James Tam Creating Tuples Format: tuple_name = (value 1, value 2...value n ) Example: tup = (1,2,"foo",0.3)

James Tam A Small Example Using Tuples The example can found in UNIX under: /home/231/examples/composites/tuples1.py tup = (1,2,"foo",0.3) print tup print tup[2] tup[2] = "bar" Error: “TypeError: object does not support item assignment”

James Tam Function Return Values Although it appears that functions in Python can return multiple values they are in fact consistent with how functions are defined in other programming languages. Functions can either return zero or exactly one value only. Specifying the return value with brackets merely returns one tuple back to the caller. def fun (): return (1,2,3) Def fun (num): if (num > 0): print “pos” return elif (num < 0): print “neg” return Returns: A tuple with three elements Nothing is returned back to the caller

James Tam Dictionaries A special purpose composite type that maps keys (which can be any immutable type) to a value (like lists it can be any value). The keys can be used to later lookup information about the value e.g., looking up the definition for a word in a dictionary.

James Tam Small Example Programs Using Dictionaries They can be found in UNIX in the directory: /home/231/examples/composites -dictionary1.py (creating dictionaries) -dictionary2.py (deleting entries from the dictionary, checking for membership)

James Tam Creating A Small Dictionary Format (defining the entire dictionary all at once) = {key 1 :value 1, key 2 :value 2...key n :value n } Example: (defining the entire dictionary all at once) dict = {"one":"yut", "two":"yee", "three":"saam"}

James Tam Creating A Large Dictionary Format: -dictionary_name = {} -dictionary_name [key 1 ] = value 1 -dictionary_name [key 2 ] = value 2 - : : : -dictionary_name [key n ] = value n Example: dict = {} dict ["word1"] = ["Dictionary definition for word1"] dict ["word2"] = ["Dictionary definition for word2"]

James Tam Examples Of Creating Dictionaries dict = {} dict ["word1"] = ["Dictionary definition for word1"] dict ["word2"] = ["Dictionary definition for word2"] dict ["word3"] = ["Dictionary definition for word3"] temp = raw_input ("Enter dictionary definition for word4: ") dict ["word4"] = [temp] print dict dict = {"one" : "yut", "two" : "yee", "three" : "saam"} print dict word = raw_input ("Enter word to translate: ") print "English:", word, "\t", "Chinese", dict[word]

James Tam Removing Dictionary Entries Format: -del [key] Example: del dict ["one"]

James Tam Example: Deletion And Checking For Membership dict = {} dict ["one"] = "Sentence one" dict ["two"] = "Sentence two" dict ["three"] = "Sentence three" if "one" in dict: print "key one is in the dictionary" del dict["one"] if "one" not in dict: print "key one is NOT in the dictionary"

James Tam You Should Now Know What is the difference between a mutable and an immutable type How strings are actually a composite type Common string functions and operations How a list can be used to store different types of information (non-homogeneous composite type) Common list operations and functions How to define an arbitrary composite type using a class What are the benefits of defining a composite type by using a class definition over using a list How to create instances of a class (instantiate) How to access and change the attributes or fields of a class What is a tuple and how do they differ from other composite types

James Tam You Should Now Know (2) How to create a tuple and access the elements Why functions at most return a single value What is a dictionary and when can they can be used How to create a dictionary, access and remove elements