Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- '''
- Examples adapted from "Programming for all, part 1: An introduction to writing for computers":
- http://arstechnica.com/science/2012/12/programming-for-all-part-1-an-introduction-to-writing-for-computers/
- and "Programming for all, part 2: From concept to code":
- http://arstechnica.com/science/2012/12/programming-for-all-part-2-from-concept-to-code/
- Most examples are fairly close to their original psuedocode; where possible, the code has been
- condensed to slightly more standard Python while preserving the original intent. Note that this
- means some of these examples aren't exactly "Pythonic," but it will make them easier to match
- to the original article. In particular, most of the variable "declarations" have been removed,
- since names are untyped in Python and may be arbitrarily assigned at any time in most cases.
- In addition, there was a bug in the Fibonacci sequence generation that I fixed (F1 == 1, not 0).
- I also skipped translation of the map and fold examples, since those are available via the
- straightforward map() and reduce() functions in Python, and you would never manipulate a list in
- such a manner anyway.
- There may be some remaining bugs (or new ones that I introduced), but I ran through all the
- examples and they seem to function as intended.
- Happy hacking!
- '''
- import argparse
- import inspect
- import sys
- def my_first_program():
- # This line is a comment to other humans
- # So is this line
- # Since function bodies can't be completely empty,
- # the following statement performs a no-op
- pass
- def my_first_useful_program():
- # store the value retrieved from user input in the variable "x"
- x = float(raw_input('What number would you like to square? '))
- x_squared = x * x # store the value of x times itself
- print 'Your number squared is', x_squared
- def is_it_hot_out():
- # store the temperature retrieved from user input
- temperature = float(raw_input('Temperature: ')) # for all we care, we are reading this from
- # a digital thermometer connected to the
- # computer, or from the Weather Channel!
- # In this Python interpretation of the example,
- # we read it from the command line.
- if temperature > 89: # here is where we decide what
- # we are going to do next
- # only one print statement (branch)
- # will be executed
- # this will be printed if temperature is above 89
- print 'Wow, it is hot outside!'
- else:
- # this will be printed if temperature is not above 89
- print "It isn't too hot, go outside"
- def is_it_nice_out():
- temperature = float(raw_input('Temperature: ')) # from command line
- if temperature > 89:
- print "Wow, it is hot outside!"
- else:
- # if it is not too hot outside, check if it is too cold
- if temperature < 40:
- print "Wow, it is cold outside!"
- else:
- print "It is nice out, you should go outside"
- def first_ten_squares():
- # count the variable i from 1 to 10 by 1
- for i in xrange(1, 11):
- # you can use exponents instead of manually squaring numbers
- print "The square of", i, "is", i ** 2
- def first_ten_squares_unrolled():
- index = 1
- print "The square of", index, "is", index ** 2
- index = 2
- print "The square of", index, "is", index ** 2
- index = 3
- print "The square of", index, "is", index ** 2
- index = 4
- print "The square of", index, "is", index ** 2
- index = 5
- print "The square of", index, "is", index ** 2
- index = 6
- print "The square of", index, "is", index ** 2
- index = 7
- print "The square of", index, "is", index ** 2
- index = 8
- print "The square of", index, "is", index ** 2
- index = 9
- print "The square of", index, "is", index ** 2
- index = 10
- print "The square of", index, "is", index ** 2
- def user_driven_squares():
- choice = "Y"
- while choice == "Y": # the == sign is the logical comparison
- # to see if two values are the same, it
- # should not be confused with the
- # assignment operator =
- x = float(raw_input("What number would you like to square? "))
- print "Your number squared is", x ** 2
- choice = raw_input("Would you like to enter another number? [Y/N] ")
- def weather_station():
- temperature1 = float(raw_input('Temperature 1: ')) # Get three temperatures
- temperature2 = float(raw_input('Temperature 2: ')) # from the user
- temperature3 = float(raw_input('Temperature 3: '))
- # algorithm step 2
- sum = temperature1 + temperature2 + temperature3
- # algorithm step 3
- averageTemp = sum / 3.0
- # steps 4 and half of 5 from the algorithm
- sqDist1 = (temperature1 - averageTemp) ** 2
- sqDist2 = (temperature2 - averageTemp) ** 2
- sqDist3 = (temperature3 - averageTemp) ** 2
- # other half of 5 and step 6 from the algorithm
- stddevTemp = ((sqDist1 + sqDist2 + sqDist3) / 3.0) ** 0.5
- print "Average temperature =", averageTemp, "+/-", stddevTemp
- def modular_weather_station():
- def computeAverage(n1, n2, n3):
- # the values passed into this function will be mapped to
- # the values n1, n2, and n3--only in this function
- sum = n1 + n2 + n3
- # at a return statement, the program will return to the
- # point where it left off
- return sum / 3.0
- def standardDeviation(n1, n2, n3, avg):
- sqDist1 = (n1 - avg) ** 2
- sqDist2 = (n2 - avg) ** 2
- sqDist3 = (n3 - avg) ** 2
- return ((sqDist1 + sqDist2 + sqDist3) / 3.0) ** 0.5
- temperature1 = float(raw_input('Temperature 1: '))
- temperature2 = float(raw_input('Temperature 2: '))
- temperature3 = float(raw_input('Temperature 3: '))
- # we will call a function that computes the average for us
- # at this line, control of the program will be transferred
- # to the computeAverage function
- averageTemp = computeAverage(temperature1, temperature2, temperature3)
- # likewise for the standard deviation
- stddevTemp = standardDeviation(temperature1, temperature2, temperature3, averageTemp)
- print "Average temperature = ", averageTemp, "+/-", stddevTemp
- def intro_to_lists():
- squareList = []
- myList = [1, 2, 3, 4, 5, 6] # Like we can set the value of a number,
- # we can set the value of a list using
- # [] and , to separate values
- # Print out myList
- for item in myList:
- print item
- # this would display the numbers 1, 2, 3, 4, 5, and 6
- # populate squareList
- for item in myList:
- # Append the square of each value in myList
- # to the end of squareList
- squareList.append(item ** 2)
- # Print out squareList
- for item in squareList:
- print item
- # this would display 1, 4, 9, 16, 25, and 36
- # modify something in squareList
- squareList[5] = 27.39
- # print again
- for item in squareList:
- print item
- # this would now print 1, 4, 9, 16, 27.39, and 36
- def list_based_weather_station():
- def computeAverage(nums):
- sum = 0
- # add up all the elements in the list
- for index in xrange(len(nums)):
- sum = sum + nums[index]
- # divide the sum by the number of elements
- return sum / len(nums)
- def standardDeviation(nums, avg):
- sum = 0
- for index in xrange(len(nums)):
- sqDist = (nums[index] - avg) ** 2
- sum = sum + sqDist
- return (sum / len(nums)) ** 0.5
- temperatures = []
- choice = "" # read in as many temperatures as the user wants!
- choice = "Y"
- while choice == "Y":
- temp = float(raw_input("Please input a temperature: "))
- # add the newest read in value to the list of temperatures
- temperatures.append(temp)
- choice = raw_input("Would you like to enter another value? [Y/N] ")
- # At this point we have a list of temperatures,
- # we don't know how long it is, but we'd like to
- # find it average and standard deviation, just like before
- # We can pass a list to a function like any other data
- averageTemp = computeAverage(temperatures)
- stddevTemp = standardDeviation(temperatures, averageTemp)
- print "Average temperature =", averageTemp, "+/-", stddevTemp
- def fibonacci():
- def computeFibonacci(n):
- if n == 0: # if we are asking for the first Fibonacci number
- return 0 # 0 is the first Fibonacci number
- elif n == 1:
- return 1 # 1 is the second Fibonacci number
- # If we are not asking for the first or second
- # Fibonacci number, then we need to compute it
- return computeFibonacci(n - 1) + computeFibonacci(n - 2) # /Neo: Woah!
- fibNumber = int(raw_input("Which Fibonacci number would you like to compute? "))
- answer = computeFibonacci(fibNumber)
- print "Fibonacci number", fibNumber, "is", answer
- def main():
- parser = argparse.ArgumentParser(
- description='Run Ars Technica programming examples',
- epilog=__doc__,
- formatter_class=argparse.RawDescriptionHelpFormatter )
- group = parser.add_mutually_exclusive_group(required=True)
- group.add_argument('-l', '--list', action='store_true', help='list examples')
- group.add_argument('example', nargs='?', metavar='EXAMPLE_NAME', help='run one example')
- group.add_argument('-a', '--all', action='store_true', help='run all examples')
- parser.add_argument('-p', '--print', action='store_true', dest='print_source', help='print source')
- args = parser.parse_args()
- examples = {}
- for member in inspect.getmembers(sys.modules[__name__]):
- if not member[0].startswith('__') and member[0] != 'main' and callable(member[1]):
- examples[member[0]] = member[1]
- if args.list:
- sys.stderr.write('Valid examples:\n{}\n'.format('\n'.join(examples.keys())))
- elif args.all:
- for example in examples:
- if args.print_source:
- print inspect.getsource(examples[example])
- else:
- examples[example]()
- print
- else:
- if args.example in examples:
- if args.print_source:
- print inspect.getsource(examples[args.example])
- else:
- examples[args.example]()
- else:
- sys.stderr.write('Valid examples:\n{}\n'.format('\n'.join(examples.keys())))
- sys.exit(1)
- if __name__ == '__main__':
- try:
- main()
- except KeyboardInterrupt:
- sys.exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement