IT45200

Untitled

May 14th, 2020
1,681
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. import collections
  2. import random
  3.  
  4.  
  5. benford_percentages = {1: 0.334, 2: 0.185, 3: 0.124,
  6.                        4: 0.075, 5: 0.071, 6: 0.065, 7: 0.055, 8: 0.049, 9: 0.042}
  7.  
  8.  
  9. def process(data):
  10.  
  11.     results = []
  12.  
  13.     first_digits_list = list(map(lambda n: str(n)[0], data))
  14.     first_digit_frequencies = collections.Counter(first_digits_list)
  15.  
  16.     for n in range(1, 10):
  17.  
  18.         data_frequency = first_digit_frequencies[str(n)]
  19.         data_frequency_percent = data_frequency / len(data) * 100
  20.         benford_frequency = len(data) * benford_percentages[n]
  21.         benford_frequency_percent = benford_percentages[n] * 100
  22.         deviation = abs(data_frequency - benford_frequency)
  23.         deviation_percent = abs(
  24.             data_frequency_percent - benford_frequency_percent)
  25.  
  26.         results.append({"n": n,
  27.                         "dfp":       data_frequency_percent,
  28.                         "bfp":    benford_frequency_percent,
  29.                         "dp": deviation_percent})
  30.     width = 36
  31.     print("-" * width)
  32.     print("| n |  Data  | Benford | Deviation |")
  33.     print("-" * width)
  34.  
  35.     for item in results:
  36.  
  37.         print("| {} | {:6.2f} | {:6.2f}  |  {:6.2f}   |".format(item["n"],
  38.                                                                 item["dfp"],
  39.                                                                 item["bfp"],
  40.                                                                 item["dp"]))
  41.     print("-" * width)
  42.  
  43.  
  44. random_data = [0] * 1000
  45.  
  46. random_data = list(map(lambda n: n + random.randint(1, 1000), random_data))
  47.  
  48. process(random_data)
Advertisement
Add Comment
Please, Sign In to add comment