Advertisement
Guest User

Untitled

a guest
Jan 1st, 2013
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.96 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. '''
  4. Examples adapted from "Programming for all, part 1: An introduction to writing for computers":
  5.  
  6. http://arstechnica.com/science/2012/12/programming-for-all-part-1-an-introduction-to-writing-for-computers/
  7.  
  8. and "Programming for all, part 2: From concept to code":
  9.  
  10. http://arstechnica.com/science/2012/12/programming-for-all-part-2-from-concept-to-code/
  11.  
  12. Most examples are fairly close to their original psuedocode; where possible, the code has been
  13. condensed to slightly more standard Python while preserving the original intent. Note that this
  14. means some of these examples aren't exactly "Pythonic," but it will make them easier to match
  15. to the original article. In particular, most of the variable "declarations" have been removed,
  16. since names are untyped in Python and may be arbitrarily assigned at any time in most cases.
  17.  
  18. In addition, there was a bug in the Fibonacci sequence generation that I fixed (F1 == 1, not 0).
  19. I also skipped translation of the map and fold examples, since those are available via the
  20. straightforward map() and reduce() functions in Python, and you would never manipulate a list in
  21. such a manner anyway.
  22.  
  23. There may be some remaining bugs (or new ones that I introduced), but I ran through all the
  24. examples and they seem to function as intended.
  25.  
  26. Happy hacking!
  27. '''
  28.  
  29. import argparse
  30. import inspect
  31. import sys
  32.  
  33.  
  34. def my_first_program():
  35.     # This line is a comment to other humans
  36.     # So is this line
  37.     # Since function bodies can't be completely empty,
  38.     # the following statement performs a no-op
  39.     pass
  40.  
  41.  
  42. def my_first_useful_program():
  43.     # store the value retrieved from user input in the variable "x"
  44.     x = float(raw_input('What number would you like to square? '))
  45.     x_squared = x * x   # store the value of x times itself
  46.     print 'Your number squared is', x_squared
  47.  
  48.  
  49. def is_it_hot_out():
  50.     # store the temperature retrieved from user input
  51.     temperature = float(raw_input('Temperature: ')) # for all we care, we are reading this from
  52.                                                     # a digital thermometer connected to the
  53.                                                     # computer, or from the Weather Channel!
  54.                                                     # In this Python interpretation of the example,
  55.                                                     # we read it from the command line.
  56.     if temperature > 89:    # here is where we decide what
  57.                             # we are going to do next
  58.                             # only one print statement (branch)
  59.                             # will be executed
  60.         # this will be printed if temperature is above 89
  61.         print 'Wow, it is hot outside!'      
  62.     else:
  63.         # this will be printed if temperature is not above 89
  64.         print "It isn't too hot, go outside"  
  65.  
  66.  
  67. def is_it_nice_out():
  68.     temperature = float(raw_input('Temperature: ')) # from command line
  69.     if temperature > 89:
  70.         print "Wow, it is hot outside!"
  71.     else:
  72.         # if it is not too hot outside, check if it is too cold
  73.         if temperature < 40:    
  74.             print "Wow, it is cold outside!"
  75.         else:
  76.             print "It is nice out, you should go outside"
  77.  
  78.  
  79. def first_ten_squares():
  80.     # count the variable i from 1 to 10 by 1
  81.     for i in xrange(1, 11):
  82.         # you can use exponents instead of manually squaring numbers
  83.         print "The square of", i, "is", i ** 2
  84.  
  85.  
  86. def first_ten_squares_unrolled():
  87.     index = 1
  88.     print "The square of", index, "is", index ** 2
  89.     index = 2
  90.     print "The square of", index, "is", index ** 2
  91.     index = 3
  92.     print "The square of", index, "is", index ** 2
  93.     index = 4
  94.     print "The square of", index, "is", index ** 2
  95.     index = 5
  96.     print "The square of", index, "is", index ** 2
  97.     index = 6
  98.     print "The square of", index, "is", index ** 2
  99.     index = 7
  100.     print "The square of", index, "is", index ** 2
  101.     index = 8
  102.     print "The square of", index, "is", index ** 2
  103.     index = 9
  104.     print "The square of", index, "is", index ** 2
  105.     index = 10
  106.     print "The square of", index, "is", index ** 2
  107.  
  108.  
  109. def user_driven_squares():
  110.     choice = "Y"
  111.     while choice == "Y":    # the == sign is the logical comparison
  112.                             # to see if two values are the same, it
  113.                             # should not be confused with the
  114.                             # assignment operator =
  115.         x = float(raw_input("What number would you like to square? "))
  116.         print "Your number squared is", x ** 2
  117.         choice = raw_input("Would you like to enter another number? [Y/N] ")
  118.  
  119.  
  120. def weather_station():
  121.     temperature1 = float(raw_input('Temperature 1: ')) # Get three temperatures
  122.     temperature2 = float(raw_input('Temperature 2: ')) # from the user
  123.     temperature3 = float(raw_input('Temperature 3: '))
  124.  
  125.     # algorithm step 2
  126.     sum = temperature1 + temperature2 + temperature3  
  127.     # algorithm step 3
  128.     averageTemp = sum / 3.0  
  129.     # steps 4 and half of 5 from the algorithm
  130.     sqDist1 = (temperature1 - averageTemp) ** 2
  131.     sqDist2 = (temperature2 - averageTemp) ** 2
  132.     sqDist3 = (temperature3 - averageTemp) ** 2
  133.     # other half of 5 and step 6 from the algorithm
  134.     stddevTemp = ((sqDist1 + sqDist2 + sqDist3) / 3.0) ** 0.5
  135.  
  136.     print "Average temperature =", averageTemp, "+/-", stddevTemp
  137.  
  138.  
  139. def modular_weather_station():
  140.  
  141.     def computeAverage(n1, n2, n3):
  142.         # the values passed into this function will be mapped to
  143.         # the values n1, n2, and n3--only in this function
  144.         sum = n1 + n2 + n3
  145.         # at a return statement, the program will return to the
  146.         # point where it left off
  147.         return sum / 3.0
  148.  
  149.     def standardDeviation(n1, n2, n3, avg):
  150.         sqDist1 = (n1 - avg) ** 2
  151.         sqDist2 = (n2 - avg) ** 2
  152.         sqDist3 = (n3 - avg) ** 2
  153.  
  154.         return ((sqDist1 + sqDist2 + sqDist3) / 3.0) ** 0.5
  155.  
  156.     temperature1 = float(raw_input('Temperature 1: '))
  157.     temperature2 = float(raw_input('Temperature 2: '))
  158.     temperature3 = float(raw_input('Temperature 3: '))
  159.  
  160.     # we will call a function that computes the average for us
  161.     # at this line, control of the program will be transferred
  162.     # to the computeAverage function
  163.     averageTemp = computeAverage(temperature1, temperature2, temperature3)
  164.  
  165.     # likewise for the standard deviation
  166.     stddevTemp = standardDeviation(temperature1, temperature2, temperature3, averageTemp)
  167.  
  168.     print "Average temperature = ", averageTemp, "+/-", stddevTemp
  169.  
  170.  
  171. def intro_to_lists():
  172.     squareList = []
  173.     myList = [1, 2, 3, 4, 5, 6] # Like we can set the value of a number,
  174.                                 # we can set the value of a list using
  175.                                 # [] and , to separate values
  176.     # Print out myList
  177.     for item in myList:
  178.         print item
  179.     # this would display the numbers 1, 2, 3, 4, 5, and 6
  180.  
  181.     # populate squareList
  182.     for item in myList:
  183.         # Append the square of each value in myList
  184.         # to the end of squareList
  185.         squareList.append(item ** 2)
  186.  
  187.     # Print out squareList
  188.     for item in squareList:
  189.         print item
  190.     # this would display 1, 4, 9, 16, 25, and 36
  191.  
  192.     # modify something in squareList
  193.     squareList[5] = 27.39
  194.     # print again
  195.     for item in squareList:
  196.         print item
  197.     # this would now print 1, 4, 9, 16, 27.39, and 36
  198.  
  199.  
  200. def list_based_weather_station():
  201.  
  202.     def computeAverage(nums):
  203.         sum = 0
  204.         # add up all the elements in the list
  205.         for index in xrange(len(nums)):
  206.             sum = sum + nums[index]
  207.         # divide the sum by the number of elements
  208.         return sum / len(nums)
  209.  
  210.     def standardDeviation(nums, avg):
  211.         sum = 0
  212.         for index in xrange(len(nums)):
  213.             sqDist = (nums[index] - avg) ** 2
  214.             sum = sum + sqDist
  215.         return (sum / len(nums)) ** 0.5
  216.  
  217.     temperatures = []
  218.     choice = ""     # read in as many temperatures as the user wants!
  219.  
  220.     choice = "Y"
  221.     while choice == "Y":
  222.         temp = float(raw_input("Please input a temperature: "))
  223.         # add the newest read in value to the list of temperatures
  224.         temperatures.append(temp)
  225.         choice = raw_input("Would you like to enter another value? [Y/N] ")
  226.     # At this point we have a list of temperatures,
  227.     # we don't know how long it is, but we'd like to
  228.     # find it average and standard deviation, just like before
  229.  
  230.     # We can pass a list to a function like any other data
  231.     averageTemp = computeAverage(temperatures)  
  232.     stddevTemp = standardDeviation(temperatures, averageTemp)
  233.  
  234.     print "Average temperature =", averageTemp, "+/-", stddevTemp
  235.  
  236.  
  237. def fibonacci():
  238.  
  239.     def computeFibonacci(n):
  240.         if n == 0:      # if we are asking for the first Fibonacci number
  241.             return 0    # 0 is the first Fibonacci number
  242.         elif n == 1:
  243.             return 1    # 1 is the second Fibonacci number
  244.         # If we are not asking for the first or second
  245.         # Fibonacci number, then we need to compute it
  246.         return computeFibonacci(n - 1) + computeFibonacci(n - 2)   # /Neo: Woah!
  247.  
  248.     fibNumber = int(raw_input("Which Fibonacci number would you like to compute? "))
  249.     answer = computeFibonacci(fibNumber)
  250.     print "Fibonacci number", fibNumber, "is", answer
  251.  
  252.  
  253.  
  254. def main():
  255.     parser = argparse.ArgumentParser(
  256.         description='Run Ars Technica programming examples',
  257.         epilog=__doc__,
  258.         formatter_class=argparse.RawDescriptionHelpFormatter )
  259.     group = parser.add_mutually_exclusive_group(required=True)
  260.     group.add_argument('-l', '--list', action='store_true', help='list examples')
  261.     group.add_argument('example', nargs='?', metavar='EXAMPLE_NAME', help='run one example')
  262.     group.add_argument('-a', '--all', action='store_true', help='run all examples')
  263.     parser.add_argument('-p', '--print', action='store_true', dest='print_source', help='print source')
  264.     args = parser.parse_args()
  265.  
  266.     examples = {}
  267.     for member in inspect.getmembers(sys.modules[__name__]):
  268.         if not member[0].startswith('__') and member[0] != 'main' and callable(member[1]):
  269.             examples[member[0]] = member[1]
  270.    
  271.     if args.list:
  272.         sys.stderr.write('Valid examples:\n{}\n'.format('\n'.join(examples.keys())))
  273.     elif args.all:
  274.         for example in examples:
  275.             if args.print_source:
  276.                 print inspect.getsource(examples[example])
  277.             else:
  278.                 examples[example]()
  279.                 print
  280.     else:
  281.         if args.example in examples:
  282.             if args.print_source:
  283.                 print inspect.getsource(examples[args.example])
  284.             else:
  285.                 examples[args.example]()
  286.         else:
  287.             sys.stderr.write('Valid examples:\n{}\n'.format('\n'.join(examples.keys())))
  288.             sys.exit(1)
  289.  
  290.  
  291. if __name__ == '__main__':
  292.     try:
  293.         main()
  294.     except KeyboardInterrupt:
  295.         sys.exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement