average.py
# Import the sys module for access to stdin and stdout.
import sys
def average(numbers):
"""averages takes a list of integers as its
argument and returns their average as a float."""
total = 0
for number in numbers:
total += int(number)
return total/float(len(numbers))
for line in sys.stdin:
# Get the average of the integers
# Since we get each line of stdin as
# a string, we use split() to give us
# a list of the individual words (which
# should all be integers).
avg = average(line.split())
# Format the output:
# Express our average to 2 decimal places, and
# also include the original line (for checking)
output = "%.2f: %s" % (avg, line)
# Write it to stdout
sys.stdout.write(output)
Calculate average of a sequence which starts from $-5$, and increments by $2$, and stops before $10$.
seq -s' ' -5 2 10 | python average.py
Generate 10 random integers within 0-1000 and calculate average:
shuf -i 0-1000 -n 10 | tr '\n' ' ' | python average.py
|