#!/usr/bin/python """A collection of my personal utility functions.""" def reverse(a_to_b): """reverse is a function to "reverse" a dictionary that has no duplicate values. It takes a dictionary as its argument. It returns another dictionary whose keys are the values of the input dictionary, and whose values are the corresponding keys of the input dictionary.""" b_to_a = {} for a in a_to_b: b = a_to_b[a] b_to_a[b] = a return b_to_a def print_dict(dict): """print_dict is a function to print the contents of a dictionary. It takes a dictionary as its argument. For each key in the dictionary it prints the key followed by the value.""" for key in dict: print key, dict[key] def find_root( function, lower, upper, tolerance ): """find_root is a function that finds the interval in which the root of a function lies by repeated bisection. It takes the following arguments: The function name, The lower and upper values of the interval in which the root lies, and The size of the returned interval (the tolerance). It returns an interval containing the root whose size is less than or equal to the supplied tolerance.""" while upper - lower > tolerance: middle = (lower + upper)/2.0 if function(upper)*function(middle) > 0.0: upper = middle else: lower = middle return (lower, upper) def file2dict(filename): """file2dict takes a file name as its argument. This file must contain pairs of words. It returns the equivalent Python dictionary.""" import sys dict={} data = None try: data = open(filename) for line in data: try: [ key, value ] = line.split() except ValueError: print "File %s is not in the correct format." % filename dict = None break dict[key] = value data.close() except IOError, error: (errno, errdetails) = error print "Problem with file %s: %s" % (filename, errdetails) print "Aborting!" if type(data) == file: data.close() sys.exit(1) return dict