Advanced Python Idioms BCHB524 Lecture 9 BCHB524 - Edwards
Outline Sequences, iteration, and iterables Comprehensions Functional Programming Exercises BCHB524 - 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 - Edwards
Iterables # sequences are iterable -> build list aList = 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 function keys = [1,2,3,4,5] values = 'abcde' aListOfPairs = zip(keys,values) print "A list of pairs:\n ",aListOfPairs # list of pairs are iterable -> build dict aDict = dict(aListOfPairs) print "A dictionary from a list of pairs\n ",aDict BCHB524 - 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 - Edwards
Enumerate # sequences are iterable -> build list aList = list('abcdefabcdef') # enumerate get index with item for i,c in enumerate(aList): print i,c # exactly equivalent to i = 0 for c in aList: print i,c i += 1 BCHB524 - Edwards
Map # Numbers in a string... split into a list numbers = '1,2,3,4,5,6' number_list = numbers.split(',') # Print the list, and manipulate its values! print number_list number_list[0] += 1 # Fix the problem, apply the int function to each item number_list = map(int,number_list) # Print the new list and check we can manipulate its values... print number_list number_list[0] += 1 print number_list # Now to print it back out print ",".join(number_list) # Fix the problem, apply the str function to each item number_list = map(str,number_list) # Print the new list and check that we can do a join print number_list print ",".join(number_list) BCHB524 - Edwards
Sorted, Reversed # Make a list aList = 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 - Edwards
Comprehensions Comprehensions build lists using iteration [ expr for item in iterable ] # Make the times two table.. timesTwo = [ 2*x for x in range(10) ] # Make it another way timesTwoToo = [] for x in range(10): timesTwoToo.append(2*x) print "timesTwo:\n ",timesTwo print "timesTwoToo:\n ",timesTwoToo l1 = [ 2*x for x in range(10) ] l2 = [] for x in range(10): l2.append(2*x) print l1 print l2 BCHB524 - 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. def f(x): return 2*x g = f print f(1),g(2),f(3),g(4) BCHB524 - Edwards
sorted, revisited The sorted function permits a keyword parameter: key key is a function which returns the sort value # Initialize a new list aList = [1,-2,3,-4,5,-6] # Print the list as is and sorted print "aList:\n ",aList print "Sorted:\n ",sorted(aList) # Define absolute value sort key def absSortKey(x): return abs(x) # Define negative value sort key def negSortKey(x): return -x # Demonstrate alternative sorting keys print "Sorted by absolute value:\n ",sorted(aList,key=absSortKey) print "Sorted by negative value:\n ",sorted(aList,key=negSortKey) BCHB524 - 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 - 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 - Edwards
Homework 5 Due Tuesday, October 10th. Submit using Canvas Make sure you work through the exercises from the lecture. Exercise 1 from Lecture 8 Exercises 1 and 2 from Lecture 9 BCHB524 - Edwards