Evaluate these expressions: ------------------------------------ 1 + 2 ** 3 2. * -2 1 / ( 2 * 3) -((4)) 8 / 4*2 1 / 3 * 3 1 + 10 % 3 0 / 0+1 What is printed by this statement: ------------------------------ print "1 + 3" What is the value of x after the following statements: ---------- x = 3 x = x + 6 x /= 2 What is the value of b after the following statements: ---------- a = 3 b = a a = 4 What gets printed by the following code fragment: --------------- x = 3 def f(): x = 4 f() print x What gets printed by the following code fragment: --------------- def f(): g() def g(); print "we eat ham and jam and spamalot" What gets printed by the following code fragment: --------------- f() ham = spam spam = "a lot" print ham, spam http://www.cs.indiana.edu/classes/a201-hayn/a/4/index.html https://www.cs.indiana.edu/classes/a201-hayn/a/rurple_lessons/en/index.html Answer A, B, or C if the corresponding function below is a correct implementation of the abs function, D if they are all correct, and E if none are correct: A: B: def a(x): def c(x): if x < 0: if x < 0: return -x x = -x return x return x C: def b(x): if x < 0: return -x else: return x Which of the following four functions returns the minimum of its two arguments? A: B: def a(x, y): def c(x, y): if x <= y: if x < y: x print x else: else: y print y C: D: def b(x,y): def d(x, y): if (x < y): if y > x: return y return x else: else: return x return y # Week 6 practice problems, by chaynes@indiana.edu ------------------------------ def message(score, goal): """ Print the message "You lose" when the score is less than 90% of the goal, the message "Close, but no prize" when the score is less than, but within 10% of, the goal, the message "You win" if the score is over the goal, but by less than 100 points, and the message "You are awesome!" when the score is 100 points or more over the goal. (Avoid using unnecessarily complicated logic in your solution.) """ #. #. #. #. #. #. #. #. def min3(x, y, z): #------------------------------------------------------------- """ Return the minimum of x, y, and z. >>> min3(3, 1, 5) 1 >>> min3(0, 8, 7) 0 >>> min3(1, 0, -5) -5 >>> """ # Use the built-in min function, but only with two arguments #. #. #. #. def min3_without_min(x, y, z): #------------------------------------------------- """ Return the minimum of x, y, and z. >>> min3_without_min(3, 1, 5) 1 >>> min3_without_min(0, 8, 7) 0 >>> min3_without_min(1, 0, -5) -5 >>> """ # Do not use any built-in functions #. #. #. #. #. #. #. #. #. def inorder(x, y, z): #---------------------------------------------------------- """ Return a boolean value indicating if the arguments are in ascending or descending order. >>> inorder(1, 3, 3) True >>> inorder(1, 1, 5) True >>> inorder(0, 3, -1) False >>> inorder(1, 0, 2) False >>> """ #... def left_justify(n, s): #--------------------------------------------------------- """ Returns a string with the characters of s followed by enough spaces for the returned string to be of length n. >>> left_justify(5, 'abc') 'abc ' >>> """ #... def powers(n): #------------------------------------------------------------------- """ Print a table of the first n powers of two, with left justification, with columns 2 and 4 characters wide, and one space between columns. >>> powers(10) 1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1024 >>> """ #. #. #. #. def center(n, s): """ Returns a string of length n containing the characters of s with space characters on either side. The number of spaces added on one side should differ by at most 1 from the number on the other side. >>> center(4, '*') ' * ' >>> # ' * ' would also be correct """ #. #. def print_star(num_spaces): """ Prints a line the given number of spaces, followed by a star. >>> print_star(3) * >>> print_star(0) * >>> """ #... def print_big_greater_than(size): """ Print a greater than sign using 2*size+1 lines with a star on each line, and the number of spaces before the star changing by two with each line. >>> print_big_greater_than(1) * * * >>> print_big_greater_than(3) * * * * * * * >>> """ #. #. #. #. #. #. #. #. def print_big_less_than(size): """ Print a greater than sign using 2*size+1 lines with a star on each line, and the number of spaces before the star changing by two with each line. >>> print_big_less_than(1) * * * >>> print_big_less_than(3) * * * * * * * >>> """ #. #. #. #. #. #. #. #. def print_fibonacci(n): """ Print the first n Fibonacci numbers, separated by spaces, and ending with a new line. The Fibonacci numbers are an infinite sequence of numbers beginning 1, 1, 2, 3, 5, 8, and so on, in which each number after the first two is the sum of the previous two (in the example 5=2+3 and 8=3+5). Assume n is at least 2. >>> print_fibonacci(5) 1 1 2 3 5 >>> print_fibonacci(20) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 >>> Fibonacci (pronounced fib-o-nachi) numbers appear in a number of places in the geometry of nature, including shell spirals and sunflowers. And as you can see, they grow fast (exponentially). """ #. #. #. #. #. #. #. #. #. #. # lab6.py by chaynes@indiana.edu import fpformat import math def print_numbers(low, hi, increment): """Print floating point numbers, one per line, starting with low. Following numbers are obtained by adding increment to the previous number. This continues up to but not including the first number greater than hi. >>> print_numbers(1, 3, .5) 1.0 1.5 2.0 2.5 3.0 >>> """ #. #. #. #. def squareroot_table(low, hi, increment): """Same as print_numbers, except that on each line the number is followed by its square root. >>> squareroot_table(1, 3, .5) 1 1.0 1.5 1.22474487139 2.0 1.41421356237 2.5 1.58113883008 3.0 1.73205080757 >>> """ #. #. #. #. def right_justify_float(x, size, precision): """Returns a string of length `size` in which the the value of `x` is right justified with `precision` digits after the decimal point. >>> right_justify_float(3.14159, 8, 3) ' 3.142' >>> """ #. #. def formatted_squareroot_table(low, hi, increment): """Same as square_root_table, except the numbers are printed with three digits of precision (after the decimal point) and right-justified in 10 columns. >>> formatted_squareroot_table(1, 3, .5) 1.000 1.000 1.500 1.225 2.000 1.414 2.500 1.581 3.000 1.732 >>> """ #. #. #. #. #. # Week 7 practice problems, by chaynes@indiana.edu def not_fun(a): """ Return False if a is a true value, and True otherwise. Do not use boolean operator. >>> not_fun('Spam') False >>> not_fun(False) True >>> """ #. #. #. #. def or_fun(a, b): """ Return True if a or b are both true values, and False otherwise. Do not use a boolean operator. >>> or_fun(True, False) True >>> or_fun(0, '') False >>> """ #. #. #. #. #. #. def blastoff(n): """ Print the integers from n down to 1, in descending order, one per line, and then print "Blastoff". >>> blastoff(2) 2 1 Blastoff >>> """ #. #. #. #. def leap_year(year): """ Return a boolean indicating if int year is a leap year. A year is a leap year if it is evenly divisible by 4 (that is, there is no remainder when divided by 4), and it is not evenly divisible by 100, with the exception that years evenly evenly divisible by 400 are leap years. >>> leap_year(2006) False >>> leap_year(2004) True >>> leap_year(1900) False >>> leap_year(2000) True >>> """ #... def lower_triangular_mult_table(n, width): """ Print an n by n multiplication table in which each column has the indicated width. The table is printed as a "lower-triangle" removing the redundancy in a full table (since a*b = b*a) by not printing values above the diagonal. >>> lower_triangular_mult_table(9, 4) 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49 8 16 24 32 40 48 56 64 9 18 27 36 45 54 63 72 81 >>> """ def lightening_distance(seconds): """ Return an estimate of the distance, in miles, to a lightening bolt, given that sound travels about 1,100 feet per second and there are 5,270 feet per mile. >>> lightening_distance(3) 0.62618595825426948 >>> """ #. def and_fun(a, b): """ Return True if a and b are both true values, and False otherwise. Do not use boolean a operator. >>> and_fun(True, False) False >>> and_fun(1, 2) True >>> """ #. #. #. #. #. #. #. def denomination_string(n, denomination_name): """ Returns a string of the form " ", where represents the integer n and is the plural form of the denomination name. Denominations are "quarter", "dime", "nickel", and "penny". >>> denomination_string(3, 'penny') '3 pennies' >>> denomination_string(1, 'penny') '1 penny' >>> denomination_string(2, 'nickel') '2 nickels' >>> """ #. #. #. #. #. #. #. def make_change(amount): """ Returns a string indicating the number of quarters, dimes, nickels, and pennies that make perfect change for the given amount (in cents). Appropriate singular and plural forms for the coin denominations are used. >>> make_change(67) '2 quarters, 1 dime, 1 nickel, 2 pennies' >>> """ quarters = amount / 25 amount = amount % 25 #. #. #. #. #. #. #. #. def pi(delta): """ Return an estimate of the value of pi, which is the sum of the infinite series of terms beginning with 4/1 - 4/3 + 4/5 - 4/7 + ... Quit when a term whose absolute value is less than delta has been added to the series. The pattern of the terms in the series repeats indefinitely: the divisor of each term is two greater than the previous term, and the sign of the terms alternate. The more terms are added the more accurate the value of pi is (until the computation is limited by the accuracy of floating point arithmetic). >>> pi(.001) 3.1420924036835256 >>> """ #. #. #. #. #. #. #. #. #. #. #. # pr8.py, by chaynes@indiana.edu import random def predicate1(a, b, c): """ Write one line that is as simple as possible and equivalent to: if a < b: if c != 3: return False else: return True else: return False """ # FYI: Calling a function a "predicate" indicates that it returns a # truth value. #. def predicate2(a, b): """ Return a boolean value indicating if a == 3 and b == 3 or a < b without using the boolean operators and or or. """ #. #. #. #. #. #. #. def whats_it_print(): """ >>> whats_it_print() #... >>> """ i = 0 s = '01234567890123456789' line = '' while i <= 10: i = i + 1 if i < 5: i = i + 3 else: line = line + s[i] + ' ' print line UPPER_CASE_SHIFT = ord('a') - ord('A') def lower(string): """ Return a string that is like the given string, but with all upper-case letters converted to lower-case. >>> lower("The Knights of Ni") 'the knights of ni' >>> """ # FYI: this is similar to the string lower() method. # # Hint: use a loop that accumulates the string to be returned. # The since lower-case letters immediately follow the upper-case letters, # conversion of upper-case letters can be done by converting to ordinal # values, adding the difference between the ordinals of 'a' and 'A', # via the above constant, and converting back. #. #. #. #. #. #. #. #. #. #. def balanced_parens(string): """ Returns a boolean value indicating if the string contains balanced parenthesis. >>> balanced_parens('(a ()(b d) + d) e') True >>> balanced_parens('(a b))') # too many right parens False >>> balanced_parens(')(') # open paren not followed by close paren False >>> """ # Algorithm: scan the characters from left to right, adding one to a count # (which starts with zero) each time a left parenthesis is spotted, # subtracting one from the count each time # a right parenthesis is spotted, and return True if the count # ends with zero and never goes negative. #. #. #. #. #. #. #. #. #. #. #. def emphasize(string): """ Return a string with the characters in the given string separated by spaces and all upper case. >>> emphasize('The Knights said Ni!') 'T H E K N I G H T S S A I D N I !' >>> """ # Hint: recall the string method upper() #. #. #. #. #. #. def shuffle(s1, s2): """Return the perfect shuffle of strings s1 and s2, starting with s1. That is, return a string that alternates the characters of s1 and s2, starting with the first character of s1. If one string is shorter, the extra characters of the longer one are appended to the result. >>> shuffle('abc', 'def') 'adbecf' >>> shuffle('abc', 'd') 'adbc' >>> shuffle('', 'a') 'a' >>> """ #. #. #. #. #. #. #. #. #. #. def digits_encode(string): """ Assume all the characters in the string are spaces or printing keyboard characters (all of which have ordinal numbers between 32 and 126). Return a string obtained by concatinating the string representations of the ordinals in the given string. >>> ord('c') 99 >>> digits_encode('cd') '99100' >>> digits_encode('Silly walk.') '83105108108121321199710810746' >>> """ #. #. #. #. #. #. def digits_decode(string): """ If s is any string of printing keyboard characters, including space, digits_decode(digits_encode(s)) returns s. >>> digits_decode(digits_encode('Silly walk.')) 'Silly walk.' >>> """ #. #. #. #. #. #. #. #. #. #. #. def random_letters(n): """ Return a string of n randomly generated lower-case letters. >>> random_letters(5) 'kvztf' >>> """ # Hint: random letters were generated in the skip_cipher function # presented in class. #. #. #. #. #. #. #. def every_nth(s, n): """ Return a string composed of every n_th character of s, starting from the first; that is, those characters with indices 0, 1*n, 2*n, ... >>> every_nth('abcdefg', 2) 'aceg' >>> every_nth('abcdefg', 3) 'adg' >>> every_nth('abcdefg', 1) 'abcdefg' >>> every_nth('abcdefg', 20) 'a' >>> """ #. #. #. #. #. #. def skip_cipher(s, n): """ Return the result of encrypting string s by inserting n randomly chosen letters before every letter of s. >>> skip_cipher('abc', 3) 'vqtavxfbcbac' >>> every_nth(skip_cipher('abc', 3)[3:], 4) 'abc' >>> """ #. #. #. #. #. #. def is_lower_case(string): """ Returns true if all the cased letters (A-Z and a-z) in string are lower case and there is at least one cased letter in string. >>> is_lower_case('aB3') False >>> is_lower_case('ab3') True >>> is_lower_case('123') False >>> """ # FYI: this is similar to the string method islower(). # # Hint: Use a while loop, with an index counter, and a boolean variable # indicating if a lower case letter has been seen. #. #. #. #. #. #. #. #. #. #. def is_palindrome(s): """Return a boolean value indicating if s is a palindrome; that is if it is equal to its reverse. >>> is_palindrome('abc') False >>> is_palindrome('aba') True >>> is_palindrome('aa') True >>> """ # Hint: use a while loop #. #. #. #. #. #. #. def main(): """In this function add a few tests for each function in the file.""" main() def whats_it_return(): """ >>> whats_it_return() #... >>> """ i = 0 s = '[812]123-4567' while i <= 10: if s[i:].isdigit(): return i i = i + 1 return -1 def surname_first(name): """ Takes a name string of the form " " and returns a string of the form ", ". >>> surname_first("John Cleese") 'Cleese, John' >>> """ #. #. def given_name_first(name): """ Takes a name string of the form ",", where may be any number (possibly zero) of spaces, and returnsa string of the form first_name last_name. >>> given_name_first("Cleese,John") 'John Cleese' >>> given_name_first("Cleese, John") 'John Cleese' >>> """ #. #. def inches(length): """ Return the number (an integer) of inches in the length string measurement.. Assume the string format is '[], where and are both non-empty sequences of digits, and is optional. >>> inches("1'3") # one foot three inches 15 >>> inches("2'") # two feet 24 >>> """ #. #. #. #. #. #. def minutes(time): """ Return the number of minutes indicated by the time string, which is in the format [h]h:mm, that is, there are one or two hour digits followed by a colon and two minutes digits. The maximum number of hours and minutes are 99 and 59, respectively. Return -1 if the time is not in this format. >>> minutes('2:05') 125 >>> minutes('10:58') 658 >>> minutes('123:45') -1 >>> minutes('2:60') -1 >>> minutes('255') -1 >>> minutes('-3:23') -1 >>> """ # Hint: the string method isdigit() returns true only if the string contains # only digits. #. #. #. #. #. #. #. #. #. def military_time(standard_time): """ Return the time represented by the string standard_time in the military time form 'hhmm', where s is in the form '[h]h:mm AM' or '[h]h:mm PM', and the hours and minutes are in the ranges 1 to 12 and 0 to 59, resp. Return None if standard_time is not in one of these forms. Note: the following tests are far from inclusive. >>> military_time('8:40 PM') '2040' >>> military_time('4:10 AM') '0410' >>> military_time('12:30 AM') '0030' >>> military_time('12:00 PM') '1200' >>> military_time('1230 PM') >>> # None returned """ #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. # Week 10 practice problems, by chaynes@indiana.edu import random def odd(n): """ Return a boolean value indicating if n is an odd number. """ #... def whats_it(n): """ >>> n = 0 >>> 1/2 n #... >>> 'Holy Grail'['o' : 'r'] #... >>> whats_it(23) #... >>> """ n % 12 print n def swap(s, s1, s2): """ Returns a string that is the same as s but with all occurrances of strings s1 and s2 swapped. >>> swap('They had spam and eggs with spam', 'spam', 'eggs') 'They had eggs and spam with eggs' >>> """ # Hint: you may assume the character chr(0) (the null character) does not # occur in any of the strings. #. #. #. def add_n(lon, n): """ Return a new list of numbers obtained by adding n to each value in the given list of numbers, lon. >>> add_n([3, 2.5, 4], 2) [5, 4.5, 6] >>> """ #. #. #. #. #. #. def max_value(lon): """ Return the maximum value of the given non-empty list of numbers. >>> max_value([1, 20, 8, -3.4]) 20 >>> max_value([3]) 3 >>> """ #. #. #. #. #. #. #. #. def elementwise_less_than(lst1, lst2): """ Return a list of boolean values that indicate if the corresponding element of lst1 is less than the corresponding element of lst2. >>> elementwise_less_than([1, 2, 'a'], [2, 0, 'b']) [True, False, True] >>> """ #. #. #. #. #. #. def slice_out_char(s, index): """ Return a string like s, but with the character at index removed. >>> slice_out_char('abc', 1) 'ac' >>> slice_out_char('a', 0) '' >>> """ #... def is_scramble(s1, s2): """ Return a boolean value indicating if s1 is a scrambled version of s2, technically called a "permutation of s2"; that is, return a string with the same characters that are in s1 (with the same frequency of occurrence), but in any order. >>> is_scramble('aab', 'aba') True >>> is_scramble('aab', 'ab') False >>> is_scramble('', 'ab') False >>> """ #. #. #. #. #. #. #. #. #. def scramble(s): """ Return a permutation of string s: a string with the same characters as s, with the same frequency, but in a random order. >>> is_scramble(scramble('aab'), 'aab') True >>> is_scramble(scramble(''), '') True >>> """ #. #. #. #. #. #. #. #. def all_true(lst): """ Return a boolean value indicating if all the values in lst are true values. >>> all_true([5, 0, True]) False >>> all_true(['a', 0.1, [3]]) True >>> """ #. #. #. #. #. #. def any_true(lst): """ Return a boolean value indicating if any value in lst is a true value. >>> any_true([5, 0, True]) True >>> any_true([0, '', False]) False >>> """ #. #. #. #. #. #. def elementwise_less_than(lst1, lst2): """ Return a list of boolean values that indicate if the corresponding element of lst1 is less than the corresponding element of lst2. >>> elementwise_less_than([1, 2, 'a'], [2, 0, 'b']) [True, False, True] >>> """ #. #. #. #. #. #. def remove_duplicates(lst): """ Return a list containing every value in lst, but with each value appearing only once in the returned list. The order of values in the returned list is the order of their first appearance in lst. >>> remove_duplicates(list('adabbaacd')) ['a', 'd', 'b', 'c'] >>> """ #. #. #. #. #. #. #. #. def add_to(lst, x): """R eplace each value in the given list of numbers with the result of adding x to the original value. >>> a = [1, -3, 5] >>> add_to(a, 2) >>> a [3, -1, 7] >>> """ #. #. #. #. def rfind_char(s, c): """ Return the index of the right-most occurrence of character c in string s, or -1 if there is no occurrence of c in s. >>> rfind_char('abad', 'a') 2 >>> rfind_char('abad', 3) -1 >>> """ #. #. #. #. #. #. def every_other(lst): """ Return a list consisting of every other value in lst, starting with the first. >>> every_other(['a', 1, 'b', 2, 'c']) ['a', 'b', 'c'] >>> """ #. #. #. #. #. #. def elementwise_or(lst1, lst2): """ Return a list of boolean values that are the logical 'or' of the corresponding boolean elements of lst1 and lst2. >>> elementwise_or([True, True, False, False], [True, False, True, False]) [True, True, True, False] >>> """ #. #. #. #. #. #. def only_not_blank(los): """ Returns a list of the non-blank (whitespace-only) strings in the given list of strings. >>> only_not_blank(['spam', ' ', '\n', 'eggs']) ['spam', 'eggs'] >>> """ #. #. #. #. #. #. #. def delete_every_other(lst): """ Delete every other element from lst starting with the first. >>> lst = [1, 2, 3, 4, 5] >>> delete_every_other(lst) >>> assert lst == [2, 4] >>> """ #. #. #. #. #. #. import random SUITS = ['Spades', 'Hearts', 'Diamonds', 'Clubs'] PIPS = ['two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] PIPS = PIPS + ['Jack', 'Queen', 'King', 'Ace'] # Ace-high order def concatinate_after_all(los, s): """ Return a list of the results of concatinating each element of the given list of strings with the string s. >>> concatinate_after_all(['a', 'b'], 'c') ['ac', 'bc'] >>> """ #. #. #. #. #. #. def full_deck(): """ Returns a list representing a deck of Anglo-American-French style playing cards. Each card is represent by a list of the form ' of ', where is 'one' through 'ten', 'Jack', 'Queen', 'King', or 'Ace', and is one of the 'Spades', 'Hearts', 'Diamonds', or 'Clubs'. A deck represents all possible combinations of pips and suits, with no duplicates, for a total of 52 cards. >>> deck = full_deck() >>> len(deck) 52 >>> deck[0:2] ['two of Spades', 'three of Spades'] >>> """ # Hint: use concatinate_after_all #. #. #. #. #. #. #. def pip(card): """ Returns the pip of card, assuming card was returned by the full_deck function. >>> pip('3 of Spades') '3' >>> """ #. #. def shuffle(cards): """ Return a list of cards that is a shuffle (reordering or permutation) of the given list of cards. """ #. #. #. #. #. #. #. NEW_DECK = full_deck() def shuffled_deck(): """ Return a shuffle of a full deck of cards. >>> equal_sets(shuffled_deck(), NEW_DECK) True >>> equal_sets(shuffled_deck(), full_deck()) True >>> """ return shuffle(NEW_DECK) def deal(cards): """ Remove and return the first (top) element from the list of cards. >>> deck = full_deck() >>> deal(deck) 'two of Spades' >>> deal(deck) 'three of Spades' >>> """ #. #. #. def equal_sets(set1, set2): """ The arguments are sets (lists without duplicate values). Returns a boolean value indicating if the sets are equal, that is, one is a shuffle (a.k.a reordering or permutation) of the other. """ # The sets may represent hands or decks of cards. # By the no-duplicates assumption, if set1 has the same number of values # as set2 and every value in set1 is in set2, then set1 is equal to # set2, and not otherwise. #. #. #. #. #. #. #. #. def deal_hand(deck, n): """ Returns a hand (list) of n cards dealt from the deck. >>> deck = shuffled_deck() >>> poker_hand = deal_hand(deck, 5) >>> equal_sets(poker_hand + deck, full_deck()) True >>> """ #. #. #. #. #. def card_wins(card1, card2): """ Returns a boolean value indicating if card1 wins over card2 in by the usual Ace-high pip ordering. Suite is ignored. """ # Hint: card with greater pip index in PIPS wins #... def test(): """ Add tests for functions in this file. """ import random import lab10 def name_elements(los): """ Return a string made of the values in the given list of strings, separated by commas (followed by a space), except the last two, which are separated by " and ". Assume lst has at least two elements. >>> name_elements(['a', 'b', 'c']) 'a, b and c' >>> """ #. #. #. #. #. #. def peace(max_tricks): """ Simulates the card game 'war' with two players, as described in http://www.pagat.com/war/war.html, but without wars: if pips of the cards exposed in a trick are the same, the cards are taken out of the game and play continues. Assume players do not reorder cards from the order in which they are dealt. The game ends if either player runs out of cards or after max_tricks have been played. The player with the most cards at the end wins. >>> peace(5) Player 2 takes three of Diamonds and eight of Clubs Player 1 takes King of Clubs and ten of Diamonds Neither player takes three of Spades and three of Hearts Player 1 takes Queen of Diamonds and two of Clubs Player 1 takes ten of Hearts and eight of Hearts Player 1 wins >>> """ #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. def war(): """ Simulates the card game 'war', as described in http://www.pagat.com/war/war.html, with option 1: If you don't have enough cards to complete the war, you lose. Players shuffle (randomly order) cards that are won before adding them to the bottom of their deck. This prevents a possibly infinite game due to a recurrent card pattern. """ #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. #. # Week 11 practice problems, by chaynes@indiana.edu def line_count(file_name): """Return the number of lines in the named file. >>> print file('data.txt').read() 3 5.4 -2 >>> line_count('data.txt') 4 >>> """ #. #. #. #. #. #. #. #. def copy_lines(in_file_name, out_file_name, start_string, stop_string): """Copy lines from the input file to the output file, starting with the first line containing the start string and stopping when a line containing the stop string is read (without writing the stop string line). If start_string is not in the file, do not even open the output file, and if the stop string is not found, write to the end of the input file. >>> print file('argument.txt').read() M: When? O: Just now. M: No you didn't! O: Yes I did! M: You didn't! O: I did! M: You didn't! >>> copy_lines('argument.txt', 'subargument.txt', 'Just', 'I did') >>> print file('subargument.txt').read() M: When? O: Just now. M: No you didn't! >>> """ #. #. #. #. #. #. #. #. #. #. #. #. import csv def print_column(csv_file_name, column_index): """Print, one per line, the values in the indicated column of the table in the Csv file. Use zero-based indexing of the columns. >>> print file('contacts.csv').read() First Name,Last Name,Suffix,Home Street,Home Street 2,Home City,Home State,Home Postal Code,Telex Sally,Porter,,4324 Hedrick Ln,,Jersy City,NJ,23403,HB Sam,Proxmire,,125 Hampton Cr,,Jefferson,NY,32084,BA Sue,Pinter,,32 Hawthorn Dr,,Jackson,MS,13034,HB >>> print_column('contacts.csv', 3) Home Street 4324 Hedrick Ln 125 Hampton Cr 32 Hawthorn Dr >>> """ # Hint: use csv module information in assignment 11. #. #. #. #. #. #. #. #. def differences(lst): """Return a list of numbers that are the differences between each successive pair of values in lst. More precisely, the i_th value in the returned list is the difference between the (i+1)_th and i_th values in the given list. The returned list is thus one shorter than lst, which may be assumed to contain at least two values. (This is the discrete counterpart of the derivative of continuously varying functions in mathematics.) >>> differences([1, 0, 5, 3]) [-1, 5, -2] >>> """ #. #. #. #. #. #. def delete_ends(lst): """Delete the first and last elements of lst. >>> los = list('abcd') >>> delete_ends(los) >>> los ['b', 'c'] >>> """ #. #. def delete_duplicates(lst): """Delete elements from lst so that no two elements have the same value, but every value that was in lst initially still remains (but only once). The values in the resulting list are in the order of their first appearance in the given lst. >>> a = list('adabbaacd') >>> delete_duplicates(a) >>> a ['a', 'd', 'b', 'c'] >>> """ #. #. #. #. #. # lab11.py, by chaynes@indiana.edu import random def write_random(file_name, max_value, num_values): """ Writes num_values random numbers, one per line, to the named file. The numbers are evenly distributed between 0 and max_value. >>> write_random('random.txt', 10, 4) >>> print file('random.txt').read() 6.1067434776 6.21454289438 1.89631011328 5.30140893185 >>> """ #. #. #. #. #. #. def sum_file(file_name): """ Return the sum of the numbers in the named file. Assume there is at most one number per line, but that some lines may contain only whitespace, and that the numbers have the syntax of Python floating point or integer literals. >>> print file('data.txt').read() 3 5.4 -2 >>> sum_file('data.txt') 6.4000000000000004 >>> """ #. #. #. #. #. #. #. #. #. def filter_file(in_file_name, out_file_name, filter_string): """ Writes to the named output file every line of the named input file that contains filter_string. You can think of it as filtering out the lines that don't contain the filter string. >>> print file('dir_list.txt').read() 60 -rwx------+ 1 Chris Ha None 61440 Apr 11 2005 Removell-xist.exe* 60 -rwx------+ 1 Chris Ha None 61440 Jul 16 18:00 Removeorg.exe* 60 -rwx------+ 1 Chris Ha None 61440 Oct 29 15:43 Removepy2exe.exe* 60 -rwx------+ 1 Chris Ha None 61440 Jul 20 14:52 Removepycrypto.exe* 60 -rwx------+ 1 Chris Ha None 61440 May 6 12:31 Removepymedia.exe* 60 -rwx------+ 1 Chris Ha None 61440 Jul 5 11:05 Removewebstring.exe* 0 drwx------+ 2 Chris Ha None 0 Oct 29 15:43 Scripts/ 0 drwx------+ 5 Chris Ha None 0 Jul 7 12:43 Share/ 0 drwxrwx---+ 7 Administ SYSTEM 0 Jul 17 21:06 Tools/ >>> filter_file('dir_list.txt', 'oct_files.txt', ' Oct ') >>> print file('oct_files.txt').read() 60 -rwx------+ 1 Chris Ha None 61440 Oct 29 15:43 Removepy2exe.exe* 0 drwx------+ 2 Chris Ha None 0 Oct 29 15:43 Scripts/ >>> """ #. #. #. #. #. #. #. #. #. #. # Week 12 practice problems, by chaynes@indiana.edu def find(lst, value): """ Return the index of the first occurrence of value in lst, or -1 if value is not in lst. >>> find(['a', 'b', 'c'], 'b') 1 >>> find(['a', 'b', 'c'], 'd') -1 >>> """ #. #. #. #. def dot_product(vector1, vector2): """Return the dot product of the given vectors (represented as equal-length lists of numbers). The dot product is the sum of the corresponding-element products. >>> assert dot_product([1, 2], [3, 4]) == 1*3 + 2*4 >>> """ #. #. #. #. def diagonal(matrix): """Return a list of the diagonal elements of matrix (those elements with equal row and column indices). The matrix must be square (equal length and width). >>> diagonal([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [1, 5, 9] >>> """ #. #. #. #. def identity_matrix(size): """Return an identity matrix of the given size. That is, a matrix with length and width equal to size and containing all zero values except for ones on the diagonal. >>> identity_matrix(3) [[1, 0, 0], [0, 1, 0], [0, 0, 1]] >>> """ #. #. #. #. #. #. def make_matrix(lst, width): """Return a table, represented as a list of row lists, each of the given width. The elements of the table are taken from the list in row order. (The list length must be a multiple of width.) >>> make_matrix([0, 1, 2, 3, 4, 5], 3) [[0, 1, 2], [3, 4, 5]] >>> """ #. #. #. #. def sum_rows(table): """Return a list whose values are the sums of the rows of table (a list of row lists of numbers. >>> sum_rows([[1, 2, 3], [4, 5, 6]]) [6, 15] >>> """ #. #. #. #. #. #. #. #. def get_column(table, column_index): """Return a list of the values in the column indicated by column_index of the table, which is a list of row lists. >>> get_column([[1, 2, 3], [4, 5, 6]], 1) [2, 5] >>> """ #. #. #. #. #. def sum_columns(table): """Return a list of values that are the sums of the columns of table, a list of rows, each of which is a list of numbers. The table contains at least one value. >>> sum_columns([[1, 2, 3], [4, 5, 6]]) [5, 7, 9] >>> sum_columns([[3]]) [3] >>> """ #. #. #. #. #. #. #. #. #. def flatten_table(table): """Return a list of the values in table (a list of row lists) using row order; that is the values in the first row, followed by those in the second row, and so on. >>> flatten_table([[1, 2, 3], [4, 5, 6]]) [1, 2, 3, 4, 5, 6] >>> """ #. #. #. #. #. def add_column(table, column): """Add column (a list of values) to table (a list of row lists), assuming the length of column is the number of rows in table. >>> t = [[1, 2], [3, 4]] >>> add_column(t, ['a', 'b']) >>> t [[1, 2, 'a'], [3, 4, 'b']] >>> """ #. #. def add_tables(table1, table2): """Return a new table whose values are the sum of the corresponding values in table1 and table2 (assuming the dimentions of table1 and table2 are the same, and non-empty). >>> t1 = [[1, 2], [3, 4]] >>> t2 = [[5, 6], [7, 8]] >>> add_tables(t1, t2) [[6, 8], [10, 12]] >>> """ #. #. #. #. #. #. #. #. #. #. def transpose(table): """Return the transpose of table; that is, a new table in which the values in the i_th row are those in the i_th column of the given table (in the same order of course). The table may be empty. Hint: use get_column. >>> transpose([[1, 2, 3], [4, 5, 6]]) [[1, 4], [2, 5], [3, 6]] >>> """ #. #. #. #. #. #. Fill in the ellipsis: # lab12.py, by chaynes@indiana.edu def int_histogram(int_list): """Prints a histogram of frequency of occurrances of values in the given list of integers. Print one line for each distinct integer value in the list. If there are n occurrances of an integer i, the format of the corresponding line is the value i, right justified in 3 columns, followed by a space, and then n stars. The lines are in increasing order of the data values. >>> data = [8, 5, 2, 8, 4, 5, 5, 2, 8, 4, 11, 5] >>> int_histogram(data) 2 ** 4 ** 5 **** 8 *** 11 * >>> """ # Hints: when passed a list of numbers, the built-in functions min and max # return the minimum and maximum number, respectively. # # The string method call s.rjust(n) returns a string that right justifies s # in n columns. #. #. #. #. #. #. #. #. #. def find_letter(s, start_index): """Find the the first letter (alpha character) in the string s, starting the search with the given index start. Return the index of this letter, or -1 if there is no letter at or after the start index. For example, in the following test the search starts with the second character, so the 'a' character is ignored, and the index of 'Z' is returned. >>> find_letter('a1 Z2', 1) 3 >>> """ # Hint: the string method call s.isalpha() returns true if all the charcters # in s are letters. #. #. #. #. #. #. def find_non_letter(s, start_index): """Find the the first non-letter (non-alpha character) in the string s, starting the search with the given index start. Return the index of this letter, or -1 if there is no non-letter at or after the start index. In the following test the search starts with the second character, and the index of the character '1' is returned. >>> find_non_letter('Palin123', 1) 5 >>> """ # Hint: this is almost the same as the find_letter function #. #. #. #. #. #. def word_list(s): """Return a list of the (non-overlapping) words in string s, where a word is defined to be a contiguous sequence of letters that is as long as possible. >>> word_list('Knights of Ni: Ni! Ni!! Ni! Ni!') ['Knights', 'of', 'Ni', 'Ni', 'Ni', 'Ni', 'Ni'] >>> """ # Hint: Use the find_letter and find_non_letter functions and an indexed # accumulating loop. #. #. #. #. #. #. #. #. #. #. #. #. def test(): """Include some tests of the functions in this file here.""" test() Submit your work via Oncourse as lab12. Assignment Due 3pm, April 10th # a12.py, by chaynes@indiana.edu import lab12 COUNT_COLUMN_INDEX = 0 WORD_COLUMN_INDEX = 1 def find_row(table, column_index, value): """Return the index of the first row in the table that contains value in the column with the given index, or -1 if there is no such row. >>> table = [[1, 'knights'], [1, 'of'], [5, 'ni']] >>> find_row(table, WORD_COLUMN_INDEX, 'ni') 2 >>> find_row(table, 0, 'Ni') -1 >>> """ #. #. #. #. def word_count(list_of_words): """Return a table with one row for each distinct word in the list of words, where the second column is the word and the first is the number of times the word occurs in the list. Words are converted to lower case for case insensitivity. >>> words = lab12.word_list('Knights of Ni: Ni! Ni!! Ni! Ni!') >>> word_count(words) [[1, 'knights'], [1, 'of'], [5, 'ni']] >>> """ #. #. #. #. #. #. #. #. #. #. def max_word_length(word_table): """Return the length of the longest word in a word table of the form returned by the word_count function. >>> table = [[1, 'knights'], [1, 'of'], [5, 'ni']] >>> max_word_length(table) 7 >>> """ #. #. #. #. #. #. def word_histogram(text_file_name, num_words): """Prints a histogram of the frequency of the most common words in the text file. Each histogram line contains the word followed by a space and then a star for each use of the word. The lines printed in order of decreasing word frequency and the histogram is cut off after num_words lines. The words are right-justified in the number of columns required for the longest histogram word. >>> print file('brave_sir_robin.txt').read() Bravely bold Sir Robin Brought forth from Camelot. He was not afraid to die, Oh, brave Sir Robin! He was not at all afraid to be killed in nasty ways. Brave, brave, brave Sir Robin. >>> # Sir Robin text from the movie "Monty Python and the Holy Grail" >>> word_histogram('brave_sir_robin.txt', 4) brave **** sir *** robin *** was ** >>> """ # Hint: use the string methods sort and reverse, and lab12.word_list #. #. #. #. #. #. #. #. #. #. #. #. #. def test(): """Tests of the functions in this file.""" # Put at one test for each function here. test() def integrate(lst): """Return a list of numbers such that each is the sum of the numbers in lst through the corresponding position. More precisely, the i_th value in the returned list is the sum of the values in lst from its beginning up to and including the i_th value in lst. (This is the discrete counterpart of integration in calculus.) >>> assert integrate([3, 5, 1]) == [3, 3+5, 3+5+1] >>> integrate([2, 1]) [2, 3] >>> """ #. #. #. #. #. #. def min_of_column(matrix, column_index): """Return the minimum of the numbers in the column of the matrix indicated by the given index, where a matrix is a non-empty list of rows, which are lists of numbers. >>> min_of_column([[2,5,1], [3,7,1], [8,2,0]], 1) 2 >>> """ #. #. #. #. #. #. def is_decimal_number(s): """Return a boolean value indicating if string s is of the form [-]dd*[.]d* or [-].dd*, where square brackets indicate optional values, d* indicates zero or more digits (characters 0 through 9, and d indicates one digit. (Strings in these forms parse as floating point numbers.) >>> is_decimal_number('.3') True >>> is_decimal_number('-.') False >>> is_decimal_number('') False >>> is_decimal_number('5') True >>> is_decimal_number('-5.3439148') True >>> is_decimal_number('0.3.4') False >>> """ # Hint: recall the string method find(string), and the string method # isdigit(string), which indicates if the string contains only digits. #. #. #. #. #. #. #. #. def find_all(lst, value): """Return a list of the indices (in numberic order) of all occurrences of value in lst. >>> find_all([1, 5, 3, 1, 2, 1], 1) [0, 3, 5] >>> """ # Hint: recall the list method append(value). #. #. #. #. #. def make_table(lst, num_cols): """Make a table with the indicated number of columns containing the elements of lst in row-order. >>> make_table(list('abcde'), 3) [['a', 'b', 'c'], ['d', 'e']] >>> """ answer = [] for index in range(len(lst)): if index % num_cols == 0: row = [] answer.append(row) row.append(lst[index]) return answer def add_command(): """Usage: python addcommand.py N1 N2 prints the sum of the numbers N1 and N2 > python addcommand.py 3.1 4 7.1 > """ # Hint: use sys.argv #. #. #. def all_digits(los): """Return a boolean value indicating if all the strings in the given list of strings contain at least one digit and nothing but digits. >>> all_digits(['1', '', '234']) False >>> all_digits(['1234', '321']) True >>> all_digits(['1.2']) False >>> """ #. #. #. #. def all_equal(lst): """Return a boolean indicating if all the values in the given list are equal (which is trivially true if the list is empty). >>> all_equal(['x', 'x', 'x']) True >>> all_equal([1]) True >>> all_equal([]) True >>> all_equal([1, 2]) False >>> """ #. #. #. #. #. #. def remove_zeros(lon): """Return a list containing those value in the given list of numbers that are not zero. >>> remove_zeros([1, 0, -3, 0, 0, 4, 1]) [1, -3, 4, 1] >>> """ #. #. #. #. #. #. def concatenate_tables(table1, table2): """Return a table whose rows are formed by concatinating corresponding rows of the given tables. Assume the tables have the same number of rows. >>> t1 = [['a'], ['b'], ['c']] >>> t2 = [[1, 2], [3, 4], [5, 6]] >>> concatenate_tables(t1, t2) [['a', 1, 2], ['b', 3, 4], ['c', 5, 6]] >>> """ #. #. #. #. def delete_column(table, column_index): """Delete from the table the indicated column and return None. >>> t = [['a', 1, 2], ['b', 3, 4], ['c', 5, 6]] >>> delete_column(t, 1) >>> t [['a', 2], ['b', 4], ['c', 6]] >>> """ # Hint: use a del statement #. #. #. def has_duplicates(lst): """Return a boolean value indicating if the list has any duplicate values. >>> has_duplicates([3, 2, 5, 2, 8]) True >>> has_duplicates([3, 2, 5, 9, 8]) False >>> """ # Hint: for best efficiency, see if two consecutive values in a sorted copy # of the list are the same. #. #. #. #. #. #. # global_temps.py, by chaynes@indiana.edu import fpformat def fahrenheit(celcius): """Convert Celcius temperature to Fahrenheit using the formula f = 9/5 c + 32. >>> fahrenheit(2) 35.600000000000001 >>> """ #. def fahrenheit_temperature_list(file_name): """Read the indicated file, containing a Celcius temperature number from the fifth column to the end of each line. Return a list of these numbers, converted to degrees Fahrenheit, in the order of the lines. >>> print file('test_data.txt', 'r').read() 1850 -0.439 1851 -0.306 1852 -0.309 >>> fahrenheit_temperature_list('test_data.txt') [31.209800000000001, 31.449200000000001, 31.4438] >>> """ #. #. #. #. #. #. #. #. def group(lst, n): """Return a list of lists containing the values in list lst, with n values per sublist (except perhaps the last). Maintain the order of the values in lst. If the length of lst is not evenly divisible by n, the last sublist will have less than n. >>> group([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]] >>> """ # Hint: use a loop to accumulate slices. Though it is an error to do simple # indexing with an index that is too large, if the stop index of a slicing # is greater than the length of the sequence, the slice just extends to the # end of the sequence. #. #. #. #. #. def average_groups(groups): """Given a list of lists of numbers, return a list of the averages of the sublists. >>> average_groups([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]) [1.0, 4.0, 7.0, 9.5] >>> """ # Hint: the built-in function sum takes a list of numbers and returns their sum. #. #. #. #. #. def graph(lon, offset, multiplier): """Print a star graph of the numbers in lon. There is one line per number. Each line begins with the number printed right-justified in 6 columns with one digit after the decimal point. After the number and a space, a number of stars are printed. The number of stars is obtained by subtracting the given offset, multiplying the result by the given multiplier, and rounding the result. >>> graph([5.4, 5.6, 5.1], 5, 10) 5.4 **** 5.6 ****** 5.1 * >>> """ # Hint: recall the built-in round and int functions, string replication # operator, and the function fpformat.fix(value, precision). #. #. #. #. #. def main(): temps = fahrenheit_temperature_list('temp_data.txt') decade_groups = group(temps, 10) average_temps = average_groups(decade_groups) graph(average_temps, 31, 10) main() def strip(s): """Remove leading and trailing whitespace from string s. Same as s.strip(). >>> strip(' a b\n\t') 'a b' >>> """ #. #. #. #. #. #. #. #. def remove_honorific(name): """Returns the given name, but without the optional honorific Mr, Ms, Dr, Miss, or Rev. The optional honorific is separated from the rest of the name by whitespace and may optionally be followed by a period [American, as opposed to English, usage]. Assume periods do not appear elsewhere in the name, and that the rest of the name may or may not contain a space. >>> remove_honorific('Mr Graham Chappman') 'Graham Chappman' >>> remove_honorific('Mr. Graham Chappman') 'Graham Chappman' >>> remove_honorific('Dr Who') 'Who' >>> remove_honorific('John Cleese') 'John Cleese' >>> remove_honorific('Mr. Whitefeather') 'Whitefeather' >>> """ # Hint: for a simpler solution, use the in operator #. #. #. #. #. #. #. #. #. #. def readlines(file_object): """Return a list of the remaining lines read from the file object. Same behavior as the file object readlines method, so calling this function has the same result as the method call file_object.readlines(). """ #. #. #. #. #. #. #.