Python Comprehension and Generators

Slides:



Advertisements
Similar presentations
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Advertisements

Introduction to Python
Chapter 2 Writing Simple Programs
Main task -write me a program
Nested Loops. Nesting Control Structures One if statement inside another one An if statement inside a loop A loop inside an if statement Control structures.
Python Control of Flow.
CPTR 124 Review for Test 1. Development Tools Editor Similar to a word processor Allows programmer to compose/save/edit source code Compiler/interpreter.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
 Expression Tree and Objects 1. Elements of Python  Literals, Strings, Tuples, Lists, …  The order of file reading  The order of execution 2.
If statements while loop for loop
8 For-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
9/14/2015BCHB Edwards Introduction to Python BCHB Lecture 4.
List comprehensions (and other shortcuts) UW CSE 160 Spring 2015.
GCSE Computing: Programming GCSE Programming Remembering Python.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
Midterm Exam Topics (Prof. Chang's section) CMSC 201.
Introduction to Computing Using Python Repetition: the for loop  Execution control structures  for loop – iterating over a sequence  range() function.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Python Simple file reading Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Simple Pythonic file reading Python has a special.
Data Structures So far, we have seen native data structures: Simple values: int, float, Boolean Sequences: Range, string, list Tuple, dictionary (chapter.
Chapter 2 Writing Simple Programs
Scientific Programming in Python -- Cheat Sheet
Introduction to Python
CSC 458– Predictive Analytics I, Fall 2017, Intro. To Python
Computer Programming Fundamentals
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Python Comprehension and Generators
Department of Computer Science,
List comprehensions (and other shortcuts) UW CSE 160 Winter 2016.
Basic operators - strings
List comprehensions (and other shortcuts) UW CSE 160 Winter 2017.
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Repetition: the for loop
Introduction to Python
More Loop Examples Functions and Parameters
Arithmetic operations, decisions and looping
Introduction to Python
Python Primer 2: Functions and Control Flow
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
CS190/295 Programming in Python for Life Sciences: Lecture 6
Python Useful Functions and Methods
List comprehensions (and other shortcuts) UW CSE 160 Spring 2018.
Chapter (3) - Looping Questions.
CISC101 Reminders Quiz 1 grading underway Next Quiz, next week.
CSC 458– Predictive Analytics I, Fall 2018, Intro. To Python
CSC1018F: Intermediate Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Introduction to Python
Python Lists and Sequences
(more) Python.
CISC101 Reminders All assignments are now posted.
Python Basics with Jupyter Notebook
Introduction to Python
Python Sets and Dictionaries
Stream.
Vocabulary Memory Cards--Sample
Repetition: the for loop
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
CSE 231 Lab 2.
Python Exceptions and bug handling
More 2D Array and Loop Examples Functions and Parameters
Python Simple file reading
Dictionary.
Introduction to Python
Presentation transcript:

Python Comprehension and Generators Peter Wad Sackett

List comprehension 1 Creating new list with other list as basis primes = [2, 3, 5, 7] doubleprimes = [2*x for x in primes] The same as doubleprimes = list() for x in primes: doubleprimes.append(2*x) Any expression (the part before the for loop) can be used. Example: A tab separated line of numbers are read from a file, convert the numbers from strings to floats. for line in datafile: numbers = [float(no) for no in line.split()] # Do something with the list of numbers

List comprehension 2 Filtering with comprehension – using if odd = [no for no in range(20) if no % 2 == 1] numbers = [1, 3, -5, 7, -9, 2, -3, -1] positives = [no for no in numbers if no > 0] Nested for loops in comprehension Example: Creating all combinations in tuples of two numbers, where no number is repeated in a combination. combi = [(x, y) for x in range(10) for y in range(10) if x != y] Flatten a list of lists (matrix) into a simple list matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flatList = [no for row in matrix for no in row] A list does not have to form the basis of the comprehension – any iterable will do, like sets or dicts.

Set and dict comprehension It works like list comprehension, just use {} instead of [] Create a set of all codons nuc = [’A’, ’T’, ’C’, ’G’] codons = { x+y+z for x in nuc for y in nuc for z in nuc } Turning a dict inside out myDict = {'a': 1, 'b': 2, 'c': 3} reverseDict = {value:key for key, value in myDict.items()} Result: {1: 'a', 2: 'b', 3: 'c'} This only works if the values of the dictionary are immutable.

Examples # This function will find the common elements of any combination of list, set or dict. # The "highest" datatype will be returned, so list+list=>list, and list+set=>set, etc. def common(param1, param2): if not isinstance(param1, (list, set, dict)): raise TypeError("First parameter is not a list, set or dict") if not isinstance(param2, (list, set, dict)): # Useful internal functions def __commonlistset(plist, pset): return [ x for x in plist if x in pset ] def __commoncollectiondict(pcollection, pdict): return { x:pdict[x] for x in pcollection if x in pdict } # Main function code - simply figure out the combination of input if isinstance(param1, list): if isinstance(param2, list): return __commonlistset(param1, set(param2)) elif isinstance(param2, set): return set(__commonlistset(param1, param2)) else: return __commoncollectiondict(param1, param2) elif isinstance(param1, set): return set(__commonlistset(param2, param1)) return param1.intersection(param2) elif isinstance(param1, dict): return __commoncollectiondict(param2, param1)

Generators Generators are your own defined iterators, like range. Generators look like functions, but they keep the state of their variables between calls, and they use yield instead of return. Also calling them again resumes execution after the yield statement. Generators deal with possibly memory issues as values are generated on the fly. Example: range(10) returns the numbers between 0 and 9, both inclusive, myrange(10) returns the numbers between 1 and 10. def myrange(number): result = 1 while result <= number: yield result result += 1 for i in myrange(10): print(i) More info: http://www.programiz.com/python-programming/generator

Examples A generator for making a random gene. Parameters are the required min and max length of the gene. Start and stop codon included. import random def randomgene(minlength, maxlength): if minlength < 2 or minlength > maxlength: raise ValueError(’Wrong minlength and/or maxlength') # Give the initial start codon yield 'ATG' stopcodons = ('TGA', 'TAG', 'TAA') # Compute codons in gene minus start/stop codons codoncount = random.randrange(minlength, maxlength+1) - 2 while codoncount > 0: codon = ’’.join([random.choice('ATCG') for i in range(3)]) if codon not in stopcodons: yield codon codoncount -= 1 # Finally give a stop codon yield random.choice(stopcodons) # Finally using it print(''.join(randomgene(40,50))) for codon in randomgene(50,100): print(codon)