Basic Python Collective variables (sequences) Lists (arrays)

Slides:



Advertisements
Similar presentations
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Advertisements

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.
23-Jun-15 Strings, Etc. Part I: String s. 2 About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects,
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Guide to Programming with Python
Strings. Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 12 More about strings 05/02/09 Python Mini-Course: Day 3 – Lesson 12.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Hossain Shahriar Announcement and reminder! Tentative date for final exam need to be fixed! Topics to be covered in this lecture(s)
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.
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.
Chapter 5 Strings CSC1310 Fall Strings Stringordered storesrepresents String is an ordered collection of characters that stores and represents text-based.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
Hossain Shahriar Announcement and reminder! Tentative date for final exam need to be fixed! We have agreed so far that it can.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
More Strings CS303E: Elements of Computers and Programming.
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.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
LECTURE 5 Strings. STRINGS We’ve already introduced the string data type a few lectures ago. Strings are subtypes of the sequence data type. Strings are.
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.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
String and Lists Dr. José M. Reyes Álamo.
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Main Points: - Working with strings. - Problem Solving.
Module 4 String and list – String traversal and comparison with examples, List operation with example, Tuples and Dictionaries-Operations and examples.
Containers and Lists CIS 40 – Introduction to Programming in Python
String Processing Upsorn Praphamontripong CS 1110
Lecture 5 Strings.
Strings Part 1 Taken from notes by Dr. Neil Moore
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CISC101 Reminders Quiz 2 this week.
Chapter 12: Text Processing
Winter 2018 CISC101 11/16/2018 CISC101 Reminders
Chapter 12: Text Processing
Perl Variables: Array Web Programming.
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
Guide to Programming with Python
10.1 Character Testing.
4. sequence data type Rocky K. C. Chang 16 September 2018
CSC 221: Introduction to Programming Fall 2018
String and Lists Dr. José M. Reyes Álamo.
Programming Training Main Points: - Working with strings.
Topics Sequences Introduction to Lists List Slicing
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Basic String Operations
CS 1111 Introduction to Programming Spring 2019
15-110: Principles of Computing
CISC101 Reminders Assignment 2 due today.
Topics Basic String Operations String Slicing
Introduction to Computer Science
String methods 26-Apr-19.
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
Python Review
Python Strings.
Topics Basic String Operations String Slicing
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Topics Basic String Operations String Slicing
STRING MANUPILATION.
Introduction to PYTHON
Introduction to Computer Science
Strings As well as tuples and ranges, there are two additional important immutable sequences: Bytes (immutable sequences of 8 ones and zeros (usually represented.
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Basic Python Collective variables (sequences) Lists (arrays) Strings (lists of characters) Dictionaries (hashes, associative arrays) BoP covers these mostly in Data Structures (p 75) Week 1

Basic Python Lists an ordered collection of items items can be any data type items do not need to all be the same type Create a list bases = [ ‘A’, ‘C’, ‘G’, ‘T’ ] bases = list( ‘A’, ‘C’, ‘G’, ‘T ’) bases = [] bases.append( ‘A’ ) bases.append( ‘C’ ) bases.append( ‘G’ ) bases.append( ‘T’ ) Week 1

Basic Python Lists Access to list elements, zero based index bases = [ ‘a’, ‘c’, ‘g’, ‘t’ ] bases[0] is a bases[3] is t bases[4] => IndexError: list index out of range negative index counts from the right print( bases[-1] ) => t print(bases) ['a', 'c', 'g', 't'] bases[0] = ‘c‘ bases[2] = ‘c‘ print( 'bases:', bases ) bases: ['c', 'c', 'c', 't'] bases[4] = ‘c’ NO, IndexError: list assignment index out of range must use bases.append[‘c’] deleting an element print(bases) ['a', 'c', 'g', 't'] del bases[1] print(bases) ['a', 'g', 't'] list.remove(‘c’) Week 1

Basic Python Lists useful functions given bases = [ ‘a’, ‘c’, ‘g’, ‘t’ ] how long is the list? len(bases) => 4 Is a known element in the list? bases.index(‘g’) => 2 ‘g’ in bases => True ‘n’ in bases => False concatenating lists extra = ['r', 'y', 'n' ] all = bases + extra print(all) => ['a', 'c', 'g', 't', 'r', 'y', 'n'] duplicating lists double = bases * 2 print(double) => ['a', 'c', 'g', 't', 'a', 'c', 'g', 't'] counting items print( double.count(‘a’) ) => 2 double.remove(‘a’) print( double.count(‘a’) ) => 1 print( double ) => ['c', 'g', 't', 'a', 'c', 'g', 't'] reverse a list bases.reverse() print(bases) print( bases ) => ['t', 'g', 'c', 'a'] Week 1

Basic Python Lists Slices – sublist of a list - list[begin:end+1] bases[0:3] => ['a', 'c', 'g'] bases[0:-1] => ['a', 'c', 'g'] bases[3:1] => No, can’t go backwards, [] Copying lists – Doesn’t work like you expect bases = [ ‘a’, ‘c’, ‘g’, ‘t’ ] save = bases bases[1] = ‘a’ print( save ) => ['a', 'a', 'g', 't'] save is not a copy! save = bases[:] bases[1] = ‘a’ print( save ) => ['a', ‘c', 'g', 't'] save is a copy! also save = list( base ) Week 1

Basic Python Lists Iterating with lists for <dummy_variable> in <list>: Second kind of loop in python for base in bases: print(‘base:’, base ) i = 0 for base in bases: print( ‘base(‘, i, ‘) =‘, base ) A new way using range for i in range( 0, 4 ): print( ‘base(‘, i, ‘) =‘, bases[i] ) for i in range( 0, len(bases) ): print( ‘base(‘, i, ‘) =‘, bases[i] ) for i in range( len(bases) ): print( ‘base(‘, i, ‘) =‘, bases[i] ) for i in range( 0, len(bases), 2 ): # every other one print( ‘base(‘, i, ‘) =‘, bases[i] ) for i in reversed(range( len(bases) ) ): # count down not up print( ‘base(‘, i, ‘) =‘, bases[i] ) Week 1

Basic Python Strings Strings are essentially a list of characters Most features/functions work just like lists bases = ‘acgt’ bases[0] => ‘a’ bases[3] => ‘t’ bases[4] => IndexError: string index out of range bases[1:3] => ‘cg’ bases[-1] => ‘t’ len(bases) => 4 ‘a’ in bases => True ‘A’ in bases => False bases.count( ‘a’ ) => 1 Iteration for strings for b in bases: print(b) for i in range( len(bases) ): print( bases[i] ) Week 1

Basic Python Strings List methods that do not work with strings append ( use +=) reverse del remove Week 1

Basic Python Strings There are many specialized methods for strings (must import string) Predefined constants string.ascii_lowercase- lowercase letters 'abcdefghijklmnopqrstuvwxyz'. string.ascii_uppercase - uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. string.ascii_letters - concatenation of the ascii_lowercase and ascii_uppercase string.digits - '0123456789' string.hexdigits - '0123456789abcdefABCDEF'. string.octdigits - '01234567'. string.punctuation - String of ASCII characters which are considered punctuation string.whitespace - all ASCII characters that are considered whitespace. includes the characters space, tab, linefeed, return, formfeed, and vertical tab. string.printable - String of ASCII characters which are considered printable combination of digits, ascii_letters, punctuation, and whitespace. Week 1

Basic Python Strings Week 1 String methods – tests str.isalnum() Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric(). str.isalpha() Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. str.isdecimal() Return true if all characters in the string are decimal characters and there is at least one character, false otherwise. str.isdigit() Return true if all characters in the string are digits and there is at least one character, false otherwise. str.islower() Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. str.isnumeric() Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise. str.isprintable() Return true if all characters in the string are printable or the string is empty, false otherwise. str.isspace() Return true if there are only whitespace characters in the string and there is at least one character, false otherwise. str.isupper() Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise. Week 1

Basic Python Strings Complete list of string methods https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str Most important (IMO) str.count(sub[, start[, end]]) Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. str.strip([chars]) str.lstrip([chars]) str.rstrip([chars]) Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: str.startswith(prefix[, start[, end]]) str.endswith(suffix[, start[, end]]) Return True if the string starts or ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. Week 1

Basic Python String methods str.join(iterable) str.lower() str.upper() Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method. str.lower() Return a copy of the string with all the cased characters converted to lowercase. str.upper() Return a copy of the string with all the cased characters converted to uppercase. str.replace(old, new[, count]) Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. str.split(sep=None, maxsplit=-1) Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns ['']. Week 1

Basic Python Dictionaries (hashes, associative arrays) a list indexed by a string instead of a number base = { ‘a’:adenine, ‘c’:cytosine’, ‘g’:’guanine’, ‘t’:’thymine’ } base = {} base[‘a’] = ‘adenine’ … base = dict() base[‘a’] = ‘adenine’ … Week 1

Basic Python Dictionaries Iterating with dictionaries for k in bases.keys(): print( ‘base(‘, k, ‘ ) =‘, bases[k] ) for v in bases.values(): print( v ) for k,v in bases.items(): print( ‘base(‘, k, ‘ ) =‘, v ) del works with dictionaries (deletes the specified key and its value) Week 1

Basic Python Other collective variables tuple – similar to a constant list, god for permanent definitions bases = ( ‘a’, ‘c’, ‘g’, ‘t’ ) a tuple can be empty a = () if it has only one item, the syntax is special a = (2, ) access values like list Week 1

Basic Python Other collective variables sets – an un ordered collection bri = set(['brazil', 'russia', 'india']) methods add() clear() copy() difference() bri.add('colombia') bri => {'brazil', 'colombia', 'russia', 'india'} sa = set(['colombia', 'brazil']) bri.difference(sa) => {'russia', 'india'} sa.difference(bri) => set() discard() remove() intersection() union() bri = bri.union(sa) bri => {'brazil', 'russia', 'india', 'colombia'} isdisjoint() issubset() issuperset() Week 1

Basic Python Week 1

Basic Python Week 1

Basic Python Week 1