Skip to content

Instantly share code, notes, and snippets.

@z-------------
Last active August 29, 2015 14:08
Show Gist options
  • Save z-------------/fea87b4948fe048705c7 to your computer and use it in GitHub Desktop.
Save z-------------/fea87b4948fe048705c7 to your computer and use it in GitHub Desktop.
Calculate all three averages in Python. Intended for command-line use.
#!/usr/bin/python3
import sys
import operator
numbers = sys.argv[1].split(",")
if len(sys.argv) > 2:
type = sys.argv[2]
else:
type = "mean"
if type == "median":
numbers.sort()
if len(numbers) % 2 == 0:
med = [numbers[round(len(numbers)/2)-1], numbers[round(len(numbers)/2)]]
else:
med = numbers[round(len(numbers)/2)]
print(med)
elif type == "mode":
occurences = {}
result = None
for n in numbers:
occurences[n] = numbers.count(n)
occurences_sorted = sorted(occurences.items(), key=operator.itemgetter(1))
occurences_sorted.reverse()
print(occurences_sorted[0][0])
else:
sum = 0
for n in numbers:
sum += float(n)
sum /= len(numbers)
print(sum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment