# This program finds the distribution of leading digits in a set # of positive integers. The program is useful for exploring the # phenomenon known as Benford's Law. # Reads integers from input file, computing a list of tallies # for the occurrences of each leading digit (0 - 9). def count_digits(file): tally = [0] * 10 for next in file.read().split(): next = int(next) tally[first_digit(next)] += 1 return tally # Reports percentages for each leading digit, excluding zeros. def report_results(tally): if tally[0] > 0: print("excluding", tally[0], "zeros") # sum of all tallies, excluding 0 total = sum(tally) - tally[0] # report percentage of each tally, excluding 0 print("Digit\tCount\tPercent") for i in range(1, len(tally)): pct = tally[i] * 100 / total print(i, tally[i], round(pct, 2), sep="\t") print("Total", total, 100.0, sep="\t") # Returns the first digit of the given integer. def first_digit(n): result = abs(n) while result >= 10: result = result // 10 return result def main(): print("Let's count those leading digits...") filename = input("input file name? ") print() with open(filename) as file: tally = count_digits(file) report_results(tally) main()