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

Chapter 2 Writing Simple Programs
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.
If statements while loop for loop
8 For-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
9/14/2015BCHB Edwards Introduction to Python BCHB Lecture 4.
List comprehensions (and other shortcuts) UW CSE 160 Spring 2015.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Introduction to Computing Using Python Repetition: the for loop  Execution control structures  for loop – iterating over a sequence  range() function.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
Python Simple file reading Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Simple Pythonic file reading Python has a special.
Python Syntax tips Henrike Zschach. 2DTU Systems Biology, Technical University of Denmark Why are we talking about syntax ’Good’ coding Good syntax should.
Data Structures So far, we have seen native data structures: Simple values: int, float, Boolean Sequences: Range, string, list Tuple, dictionary (chapter.
Scientific Programming in Python -- Cheat Sheet
COMPSCI 107 Computer Science Fundamentals
BCH339N Systems Biology/Bioinformatics
Python Loops and Iteration
CSC 458– Predictive Analytics I, Fall 2017, Intro. To Python
Computer Programming Fundamentals
Loops BIS1523 – Lecture 10.
Department of Computer Science
loops for loops iterate over a given sequence.
Department of Computer Science,
List comprehensions (and other shortcuts) UW CSE 160 Winter 2016.
Basic operators - strings
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
Python Useful Functions and Methods
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
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.
CSC 458– Predictive Analytics I, Fall 2018, Intro. To Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Introduction to Python
Dictionaries Dictionary: object that stores a collection of data
Python Lists and Sequences
(more) Python.
CISC101 Reminders All assignments are now posted.
JavaScript: Control Statements II
Python Comprehension and Generators
Vocabulary Memory Cards--Sample
Repetition: the for loop
The structure of programming
For Loops Pages
CSE 231 Lab 6.
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Functions Functions being objects means functions can be passed into other functions: sort (list, key=str.upper)
CSE 231 Lab 2.
Thinking procedurally
BCH339N Systems Biology/Bioinformatics
Python Exceptions and bug handling
Python Simple file reading
BCH364C/394P Systems Biology/Bioinformatics
Dictionary.
Introduction to Python
Tuple.
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.

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 issue as values are generated in 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

Example: Generating a random gene sequence import random def randomgene(minlength, maxlength): yield 'ATG' counter = 2 while counter < maxlength: codon = random.choice('ATCG') + random.choice('ATCG') + random.choice('ATCG') if codon in ['TGA', 'TAG', 'TAA']: if counter >= minlength: yield codon return else: counter += 1 yield random.choice(['TGA', 'TAG', 'TAA']) # Finally using it print(''.join(randomgene(40,50)))

Example: Generating a random gene sequence, take 2 import random def randomgene(minlength, maxlength): if minlength < 2 or minlength > maxlength: raise ValueError(’Wrong minlength and/or maxlength') yield 'ATG' stopcodons = ('TGA', 'TAG', 'TAA') countdown = random.randrange(minlength, maxlength+1) - 2 while countdown > 0: codon = random.choice('ATCG') + random.choice('ATCG') + random.choice('ATCG') if codon not in stopcodons: yield codon countdown -= 1 yield random.choice(stopcodons) # Finally using it print(''.join(randomgene(40,50)))