am_dot_com

IA / AI 2022-10-19

Oct 19th, 2022 (edited)
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. # 5.py Basic Statistics
  2. class BasicStatistics:
  3. @staticmethod
  4. def sumOfAll(pCol):
  5. sum=0
  6. # iterable walk from 0 to length of pCol-1
  7. for idx in range(len(pCol)):
  8. currentValue = pCol[idx]
  9. sum += currentValue
  10. # for
  11. return sum
  12. # def sumOfAll
  13.  
  14. @staticmethod
  15. def sum (pCol):
  16. sum = 0
  17. for n in pCol:
  18. sum += n
  19. # for
  20. return sum
  21. # def sum
  22.  
  23. @staticmethod
  24. def average(pCol):
  25. try:
  26. return BasicStatistics.sum(pCol)/len(pCol)
  27. except Exception as e:
  28. return "Empty collection. Average not Computable."
  29. # def average
  30.  
  31. @staticmethod
  32. def minValue(pCol):
  33. try:
  34. return min(pCol)
  35. except:
  36. return "Empty collection. Min not computable."
  37. # def minValue
  38.  
  39. @staticmethod
  40. def maxValue(pCol):
  41. try:
  42. return max(pCol)
  43. except:
  44. return "Empty colletion. Max not computable."
  45. # def maxValue
  46.  
  47. @staticmethod
  48. def variance(pCol):
  49. sumOfSquaredDistances = 0
  50. mean = BasicStatistics.average(pCol)
  51. bOKMean = type(mean)!=str
  52. if (bOKMean):
  53. for n in pCol:
  54. dist = n-mean
  55. distSquared = dist**2
  56. sumOfSquaredDistances += distSquared
  57. # for
  58. # if
  59. try:
  60. return sumOfSquaredDistances / len(pCol)
  61. except Exception as e:
  62. strMsg = f"Exception: {str(e)}\n"
  63. strMsg += f"Variance not computable.\n"
  64. return strMsg
  65. # try-except
  66. # def variance
  67.  
  68. @staticmethod
  69. def standardDeviation(pCol):
  70. v = BasicStatistics.variance(pCol)
  71. bOKVariance = type(v)!=str
  72. if (bOKVariance):
  73. import math
  74. return math.sqrt(v)
  75. #return v**(1/2)
  76. # if
  77. # def standardDeviation
  78. # class BasicStatistics
  79.  
  80. someNumbers = [10, 20, 30]
  81. theSum = BasicStatistics.sum(someNumbers)
  82. theAverage = BasicStatistics.average(someNumbers)
  83. theMin = BasicStatistics.minValue(someNumbers)
  84. theMax = BasicStatistics.maxValue(someNumbers)
  85. theVariance = BasicStatistics.variance(someNumbers)
  86. theStandardDevPop = BasicStatistics.standardDeviation(someNumbers)
  87.  
  88. strMsg = f"Some stats about these numbers {someNumbers}\n"
  89. strMsg+=f"Sum: {theSum}\n"
  90. strMsg+=f"Average: {theAverage}\n"
  91. strMsg+=f"Min: {theMin}\n"
  92. strMsg+=f"Max: {theMax}\n"
  93. strMsg+=f"Variance: {theVariance}\n"
  94. strMsg+=f"Standard Deviation: {theStandardDevPop}\n"
  95. print(strMsg)
Advertisement
Add Comment
Please, Sign In to add comment