130 likes | 258 Views
Advanced Python Idioms. BCHB524 2013 Lecture 9. Outline. Sequences, iteration, and iterables Comprehensions Functional Programming Exercises. Sequences and Iterables. Anything that supports: Iterables we know about: Strings, lists, sets, tuples Dictionaries (keys(), values(), items())
E N D
Advanced Python Idioms BCHB5242013Lecture 9 BCHB524 - 2013 - Edwards
Outline • Sequences, iteration, and iterables • Comprehensions • Functional Programming • Exercises BCHB524 - 2013 - Edwards
Sequences and Iterables • Anything that supports: • Iterables we know about: • Strings, lists, sets, tuples • Dictionaries (keys(), values(), items()) • Files (line by line) • Iterable → list, Iterable → set, etc. • Pair iterable → dictionary! BCHB524 - 2013 - Edwards
Iterables # sequences are iterable -> build listaList = list('abcdefabcdef')print"String abcdefabcdef as a list:\n ",aList# sequences are iterable -> build set (no duplicates)aSet = set('abcdefabcdef')print"String abcdefabcdef as a set:\n ",aSet# Two iterables can be paired up using the zip functionkeys = [1,2,3,4,5]values = 'abcde'aListOfPairs = zip(keys,values)print"A list of pairs:\n ",aListOfPairs# list of pairs are iterable -> build dictaDict = dict(aListOfPairs)print"A dictionary from a list of pairs\n ",aDict BCHB524 - 2013 - Edwards
Special Iterable Functions • zip • merges two or more iterables • enumerate • iterates over (index of item, item) • sum, max, min, all, any • single value from many • map, filter • Applies function or test to each element • sorted, reversed • provides the items in sorted or reversed order BCHB524 - 2013 - Edwards
Enumerate # sequences are iterable -> build listaList = list('abcdefabcdef')# enumerate get index with itemfor i,c inenumerate(aList):print i,c# exactly equivalent toi = 0for c in aList:print i,c i += 1 BCHB524 - 2013 - Edwards
Map # Numbers in a string... split into a listnumbers = '1,2,3,4,5,6'number_list = numbers.split(',')# Print the list, and manipulate its values!print number_listnumber_list[0] += 1# Fix the problem, apply the int function to each itemnumber_list = map(int,number_list)# Print the new list and check we can manipulate its values...print number_listnumber_list[0] += 1print number_list# Now to print it back outprint",".join(number_list)# Fix the problem, apply the str function to each itemnumber_list = map(str,number_list)# Print the new list and check that we can do a joinprint number_listprint",".join(number_list) BCHB524 - 2013 - Edwards
Sorted, Reversed # Make a listaList = list('abcdefabcdef')print"aList:\n ",aList# print the list sorted and reversed...print"Sorted:\n ",sorted(aList)print"Reversed:\n ",reversed(aList)print"Reversed in list:\n ",list(reversed(aList)) BCHB524 - 2013 - Edwards
Comprehensions • Comprehensions build lists using iteration[ expr for item in iterable ] # Make the times two table..timesTwo = [ 2*x for x inrange(10) ]# Make it another waytimesTwoToo = []for x inrange(10): timesTwoToo.append(2*x)print"timesTwo:\n ",timesTwoprint"timesTwoToo:\n ",timesTwoToo BCHB524 - 2013 - Edwards
Functional Programming • Python lets us treat functions as a basic immutable data-type. • We can’t change them after they are defined, but we can pass them in to functions. deff(x):return 2*xg = fprint f(1),g(2),f(3),g(4) BCHB524 - 2013 - Edwards
sorted, revisited • The sorted function permits a keyword parameter: key • key is a function which returns the sort value # Initialize a new listaList = [1,-2,3,-4,5,-6]# Print the list as is and sortedprint"aList:\n ",aListprint"Sorted:\n ",sorted(aList)# Define absolute value sort keydefabsSortKey(x):returnabs(x)# Define negative value sort keydefnegSortKey(x):return -x# Demonstrate alternative sorting keysprint"Sorted by absolute value:\n ",sorted(aList,key=absSortKey)print"Sorted by negative value:\n ",sorted(aList,key=negSortKey) BCHB524 - 2013 - Edwards
Lambda functions • Sometimes, the functions are so simple, we don’t want to define them formally. • Usually used with sorted… • Useful key functions: • Case insensitive:sorted(words,key=lambda s: s.lower()) • By dictionary value:sorted(dict.items(),key=lambda p: p[1]) • Also useful for map:map(lambda x: 2*x, (1,2,3,4,5,6)) BCHB524 - 2013 - Edwards
Exercises • Write a reverse complement function (and package it up as a program) as compactly as possible, using the techniques introduced today. • Hint: Use a dictionary for complement, map to apply the get method, reversed, and join. • Write a program to compute and output the frequency of each nucleotide in a DNA sequence using a dictionary (see lec. 8). • Output the frequencies in most-occurrences to least-occurrences order. BCHB524 - 2013 - Edwards