Advertisement
makispaiktis

Statistics in multidigit numbers

Mar 25th, 2022 (edited)
1,282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. from random import randrange
  2. from matplotlib import pyplot as plt
  3.  
  4. # Auxiliary Functions
  5. # 1. Find unique digits of a number
  6. def unique(number):
  7.     a = str(number)
  8.     b = [int(element) for element in a]
  9.     digits = sorted(b)
  10.     un = list()
  11.     for digit in digits:
  12.         if digit not in un:
  13.             un.append(digit)
  14.     return len(un)
  15.  
  16. # 2. Simulate for different numbers with fixed length = num of digits
  17. def simulate_fixed_length(sims, num_digits):
  18.     # This list will be a list with len = 10.
  19.     # Element in index 0 is the total number of cases our randomly created
  20.     # numbers had only 1 digit, index 2 for a 2-unique-digit number and
  21.     # index 9 if all the digits are different (10).
  22.     counter = [0 for i in range(10)]
  23.     start = 10 ** (num_digits - 1)
  24.     stop = 10 ** num_digits
  25.     for i in range(sims):
  26.         r = randrange(start, stop)
  27.         UN = unique(r)
  28.         counter[UN - 1] += 1
  29.         # if UN == 1:
  30.             # print(r)
  31.     return counter
  32.  
  33. # 3. Simulate for different lengths
  34. def simulate(sims, num_digits_list):
  35.     counters = list()
  36.     for num_digit in num_digits_list:
  37.         print("******************************************************")
  38.         print("For " + str(num_digit) + "-digit numbers:")
  39.         counter = simulate_fixed_length(sims, num_digit)
  40.         counters.append(counter)
  41.         print(counter)
  42.         print()
  43.     return counters
  44.  
  45. # MAIN FUNCTION
  46. sims = 10**5
  47. num_digits_list = range(2, 15)
  48. counters = simulate(sims, num_digits_list)
  49. # Plotting
  50. x = range(1, 11)
  51. plt.figure()
  52. for i in range(len(counters)):
  53.     y = counters[i]
  54.     print(y)
  55.     plt.plot(x, y)
  56.  
  57. plt.title("Simulations = " + str(sims))
  58. titles = [str(i) + "-digit numbers" for i in num_digits_list]
  59. plt.legend(titles)
  60. plt.show()
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement