corot7b2

Estatística

Jan 8th, 2022 (edited)
617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.61 KB | None | 0 0
  1. #!/usr/bin env python3
  2.  
  3. # concluido dia 8 de janeiro de 2022
  4. #---------------------
  5. #autor - bruno da silva santos
  6. #---------------------
  7. # script para o cálculo de valores de tabela de frequencia
  8. # todos os calculos aqui utilizados foram dados em aula de estatistica da universidade estadual do maranhão - UEMA
  9. #----------------------------------------------------------------------------------------------------------------
  10. #Voce pode modificar este codigo de acordo com as suas necessidades, mantendo é claro, os créditos do criador original
  11.  
  12. import sys
  13. import math
  14. from typing import List
  15. from random import randint
  16. from colorama import Fore, Back, Style
  17.  
  18.  
  19. Lista1 = [0] * 4
  20. ListaG = [0] * 5
  21. ListaH = [0] * 5
  22. ListaI = [0] * 5
  23.  
  24.  
  25.  
  26. def Q3(h):
  27.     li = ListaI[3]
  28.     qi = ListaI[0]
  29.     fiqi = ListaI[4]
  30.     fantQ = ListaI[1]
  31.  
  32.     qi = li +((qi - fantQ)/fiqi)*h
  33.     qi = round(qi,1)
  34.     return qi
  35.  
  36. def Qii(h):
  37.     li = ListaH[3]
  38.     qi = ListaH[0]
  39.     fiqi = ListaH[4]
  40.     fantQ =ListaH[1]
  41.     qi = li +((qi - fantQ)/fiqi)*h
  42.     qi = round(qi,1)
  43.     return qi
  44. def Qi(h):
  45.     li = ListaG[3]
  46.     qi = ListaG[0]
  47.     fiqi = ListaG[4]
  48.     fantQ = ListaG[1]
  49.     qi = li +((qi -fantQ)/fiqi)*h
  50.     qi = round(qi,1)
  51.     return qi
  52.  
  53. def Variancia(dv):
  54.     S = math.sqrt(dv)
  55.     return round(S,1)
  56. def DesvioPadrao(SXi2Fi,SXiFi,total):
  57.  
  58.     step1 = 1/(total-1)
  59.     step2 = SXi2Fi - ((math.pow(SXiFi,2)/total))
  60.     Dv = math.sqrt(step1*step2)
  61.     Dv = round(Dv,1)
  62.     return Dv
  63. def Media(SXiFi,total):
  64.     media = round((SXiFi/total),1)
  65.     return media
  66. def SomatorioXi2Fi(Xi2Fi):
  67.     Somatorio = 0
  68.     contador = 0
  69.     total = len(Xi2Fi)
  70.    
  71.     while contador < total:
  72.         Somatorio +=Xi2Fi[contador]
  73.         contador +=1
  74.     return round(Somatorio,1)
  75.  
  76. def SomatorioXiFi(XiFi):
  77.  
  78.     Somatorio = 0
  79.     contador = 0
  80.     total = len(XiFi)
  81.    
  82.     while contador < total:
  83.         Somatorio +=XiFi[contador]
  84.         contador +=1
  85.     return round(Somatorio,1)
  86.  
  87. def XI2FI(xi2,fi):
  88.  
  89.     contador = 0
  90.     total = len(xi2)
  91.     ListaRetorno = [0] * total
  92.  
  93.     while contador < total:
  94.         ListaRetorno[contador] = round(xi2[contador]*fi[contador],1)
  95.         contador +=1
  96.     return ListaRetorno
  97.  
  98. def XIxFI(ListaFi,ListaXi):
  99.  
  100.     contador  = 0
  101.     total = len(ListaXi)
  102.     ListaRetorno = [0]*total
  103.     while contador < total:
  104.         ListaRetorno[contador] = round(ListaFi[contador] * ListaXi[contador],1)
  105.         contador +=1
  106.     return ListaRetorno
  107.  
  108. def Xi_2(Lista):#xi ao quadrado
  109.  
  110.     ListaXi2 = [0] * len(Lista)
  111.     contador = 0
  112.     valor = None
  113.  
  114.     while contador < len(Lista):
  115.         Valor = Lista[contador]
  116.         ListaXi2[contador] = round(math.pow(Valor,2),1)
  117.         contador +=1
  118.  
  119.     return ListaXi2
  120.  
  121. def Xi(Lista,h,k):
  122.  
  123.     Menor = min(Lista)
  124.     Maior = max(Lista)
  125.     Proximo = (h + Menor)
  126.     xi = None
  127.     contador = 0
  128.     ListaXi = [0] * (int(k)+1)
  129.  
  130.     while contador < (int(k)+1):
  131.  
  132.         xi = (Menor+Proximo)/2
  133.         Menor = Proximo
  134.         Proximo = Menor +h
  135.         ListaXi[contador] = round(xi,1)
  136.         contador +=1
  137.    
  138.     return ListaXi
  139.  
  140.    
  141. def Classes(h,Lista,K):
  142.    
  143.     H = h
  144.    
  145.     Menor = min(Lista)
  146.     Maior = max(Lista)
  147.     Proximo = Menor+H
  148.     Tamanho = len(Lista)
  149.     Fac = 0
  150.     Fr  = 0
  151.     Fi = 0
  152.     ListaFi = [0] *round((int(K)+2))
  153.     contador = 0
  154.     contadorFi = 0
  155.     xi = (Menor+Maior)/2
  156.     xi_fi = 0
  157.     xi2_fi = 0
  158.     x_tmp = 0
  159.     #para quartil 1
  160.     Qi = (Tamanho/4)
  161.     CQi = 0
  162.     contador_Qi = 0
  163.     Li = 0
  164.     FantQ = 0
  165.     FiQi = 0
  166.     ListaQi = [0]*5
  167.     ListaQi[0] = Qi
  168.     #para quartil 2
  169.     Qii = (Tamanho/2)
  170.     CQii = 0
  171.     FantQii = 0
  172.     ListaQii = [0] * 5
  173.     ListaQii[0] = Qii
  174.     contador_Qii = 0
  175.     Lii = 0
  176.     FiQii = 0
  177.     #para quartil 3
  178.     Q3 = (Tamanho*3)/4
  179.     _CQii = 0
  180.     FantQ3 = 0
  181.     ListaQ3 = [0] * 5
  182.     ListaQ3[0] = Q3
  183.     contador_Q3 = 0
  184.     FiQ3 = 0
  185.     L3 = 0
  186.  
  187.     while contador < (Maior + H):
  188.    
  189.         for x in Lista:
  190.            
  191.             if float(x) >= Menor and float(x) < Proximo:
  192.                 Fi  = Fi + 1
  193.                 Fac = Fac + 1
  194.             elif float(x) == Proximo:
  195.                 break
  196.         Fr = (Fi/Tamanho) * 100
  197.         Fr = round(Fr)
  198.         xi = round((Menor+Proximo)/2,1)
  199.         x_tmp = math.pow(xi,2)
  200.         xi2_fi = round(x_tmp*Fi,1)
  201.         xi_fi = round(xi*Fi,1)
  202.         Menor = float(Menor)
  203.        
  204.        
  205.  
  206.         print (round(Menor,1),"->",round(Proximo,1),Back.WHITE+"        "+Style.RESET_ALL,Fi,Back.WHITE+ "        "+Style.RESET_ALL,Fac,Back.WHITE+"        "+Style.RESET_ALL,Fr,"%",Back.WHITE+"        "+Style.RESET_ALL,xi,Back.WHITE+"        "+Style.RESET_ALL,xi_fi,Back.WHITE+"        "+Style.RESET_ALL,xi2_fi)
  207.         print (Back.RED+"-----------------------------------------------------------------------------------------------------------"+Style.RESET_ALL)
  208.         Fr = 0
  209.         xi_fi = 0.0
  210.         xi = 0.0
  211.         if Fac == Qi:
  212.             CQi = Fac
  213.         elif Fac < Qi:
  214.             FantQ = Fac
  215.             ListaQi[1] = FantQ
  216.         if Fac > Qi and contador_Qi == 0:
  217.             CQi = Fac
  218.             FiQi = Fi
  219.             ListaQi[2] = CQi
  220.             contador_Qi +=1
  221.             Li = Menor
  222.             ListaQi[3] = Li
  223.             ListaQi[4] = FiQi
  224.         if Fac == Qii:
  225.             CQii = Fac
  226.         elif Fac < Qii:
  227.             FantQii = Fac
  228.             ListaQii[1] = FantQii
  229.         if Fac > Qii and contador_Qii == 0:
  230.             CQii = Fac
  231.             FiQii = Fi
  232.             ListaQii[2] = CQii
  233.             contador_Qii +=1
  234.             Lii = Menor
  235.             ListaQii[3] = Lii
  236.             ListaQii[4] = FiQii
  237.         if Fac == Q3:
  238.             _CQii = Fac
  239.         elif Fac < Q3:
  240.             FantQ3 = Fac
  241.             ListaQ3[1] = FantQ3
  242.         if Fac > Q3 and contador_Q3 == 0:
  243.             _CQii = Fac
  244.             FiQ3 =  Fi
  245.             ListaQ3[2] = _CQii
  246.             contador_Q3 +=1
  247.             L3 = Menor
  248.             ListaQ3[3] = L3
  249.             ListaQ3[4] = FiQ3
  250.        
  251.         ListaFi[contadorFi] = Fi
  252.         contadorFi +=1
  253.         Menor = Proximo
  254.         Proximo = Menor + H
  255.         Fi = 0
  256.         contador = Proximo
  257.     #transerindo valores dos quartis para as listas globais
  258.     xcontador = 0
  259.     for x in ListaQi:
  260.         ListaG[xcontador] = x
  261.         xcontador +=1
  262.     ycontador = 0
  263.     for y in ListaQii:
  264.         ListaH[ycontador] = y
  265.         ycontador +=1
  266.     zcontador = 0
  267.     for z in ListaQ3:
  268.         ListaI[zcontador] = z
  269.         zcontador +=1
  270.     #fim da transferencia
  271.    
  272.     return ListaFi
  273.  
  274. def Intervalor(r,k): # calculando o valor de H
  275.     h = r / k
  276.     return round(h,1)
  277.  
  278. def Anselmo(n): # FORMULA DE ANSELMO
  279.     K = ((1 + (3.32*(math.log10(n))))/2)*math.log(n)
  280.     return K
  281.  
  282. def Sturges(n):# Formula de Sturges
  283.     K = 1 + (3.32*(math.log10(n)))
  284.     return K
  285.  
  286. def ControleF(n,x):# controleF ira gerenciar a entrada da formula
  287.     K = None
  288.  
  289.     if x == 's':
  290.         K = Sturges(n)
  291.     elif x == 'a':
  292.        K = Anselmo(n)
  293.     else:
  294.         pass
  295.     return round(K,1)
  296.  
  297. def Ranger(Lista):# calcula o ranger
  298.     menor = min(Lista)
  299.     maior = max(Lista)
  300.     ranger = maior - menor
  301.     return round(ranger,1)
  302.  
  303. def Sort(Lista):#ordena a lista
  304.  
  305.     menor = None
  306.     contador = 0
  307.     Lista_x = [0]*len(Lista)
  308.  
  309.     while len(Lista) > 0:
  310.         menor = min(Lista)
  311.         indez = Lista.index(menor)
  312.         retirado = Lista.pop(indez)
  313.         Lista_x[contador] = retirado
  314.         contador +=1
  315.     return Lista_x
  316. def LerArquivo(Lista):# ler um arquivo passado pelo usuario
  317.  
  318.     print ("Digite abaixo o caminho do e o nome")
  319.     print ("Exemplo: /home/fulano/Documentos/lista.txt")
  320.     nome = input(":>")
  321.     abrir = open(nome,"r")
  322.    
  323.     #percorrendo arquivo para saber o tamanho
  324.     Tamanho = 0
  325.     Tipo = Lista[1]
  326.    
  327.     for x in abrir:
  328.         Tamanho +=1
  329.        
  330.    
  331.     abrir.close()
  332.     abrir = open(nome,"r")
  333.    
  334.     ListaRetorno = [0]*Tamanho
  335.     contador = 0
  336.  
  337.     if Tipo == 'i':
  338.         print (Fore.GREEN+"[+] Coletando valores inteiros"+Style.RESET_ALL)
  339.         for x in abrir:
  340.             ListaRetorno[contador] = int(x)
  341.             contador +=1
  342.         print (Fore.GREEN+"[+] Valores coletados com sucesso!"+Style.RESET_ALL)
  343.     elif Tipo == 'd':
  344.         print (Fore.GREEN+"[+] Coletando valores decimais"+Style.RESET_ALL)
  345.         for x in abrir:
  346.             ListaRetorno[contador] = float(x)
  347.             contador +=1
  348.         print (Fore.GREEN+"[+] Valcores coletados com sucesso!"+Style.RESET_ALL)
  349.     else:
  350.         print (Fore.YELLOW+"[!] O valores do arquivo nao sao inteiros nem decimais, tente informar um arquivo valido!"+Style.RESET_ALL)
  351.         sys.exit(0)
  352.     abrir.close()
  353.     Lista[3] = str(Tamanho)
  354.     Lista1 = Lista
  355.    
  356.     return ListaRetorno
  357.  
  358.  
  359. def Entrada_a_Decimal(q):# entrada automatica de valores decimais
  360.     print("Iniciando a entrada automatica de valores aleatorios decimais")
  361.     _q = int(q)
  362.     Lista = [0]* _q
  363.     contador = 0
  364.     tmp = 0.5
  365.     valor = 0
  366.     while contador < _q:
  367.         valor= randint(0,10)
  368.         Lista[contador] = round(valor + tmp,1)
  369.        
  370.         if randint(0,1) == 1 and tmp < 0.5:
  371.             tmp +=0.5
  372.         else:
  373.             tmp -=0.1
  374.         contador +=1
  375.     return Lista
  376.  
  377. def Entrada_a_Inteiro(q):# entrada automatica de valores inteiros
  378.     print ("Iniciando a entrada automatica de valroes aletorios inteiros")
  379.     _q = int(q)
  380.     Lista = [0] * _q
  381.     contador = 0
  382.     while contador < _q:
  383.         Lista[contador] = randint(1,100)
  384.         contador +=1
  385.     return Lista
  386.  
  387. def Entrada_m_Decimal(q):# entrada manual de valores decimais
  388.    
  389.     _q = int(q)
  390.     Lista = [0] * _q
  391.     contador = 0
  392.     valor = None
  393.     print ("Iniciando a entrada manual com valores decimais")
  394.     try:
  395.         while contador < _q:
  396.             print("Insira o valor ",contador+1)
  397.             Valor = input(":>")
  398.             Lista[contador] = float(Valor)
  399.             contador +=1
  400.     except:
  401.         print (Fore.YELLOW+"Nesta parte er permitido apenas valores inteiros!"+Style.RESET_ALL)
  402.         sys.exit(0)
  403.     return Lista
  404.  
  405. def Entrada_m_Inteiro(q):# entrada manual de valores inteiros
  406.     _q = int(q)
  407.     Lista = [0] * _q
  408.     contador = 0
  409.     print("Iniciando entrada manual com valores inteiros")
  410.     try:
  411.         while contador < _q:
  412.             print("Insira o valor ",contador+1)
  413.             Lista[contador] = int(input(":>"))
  414.             contador +=1
  415.     except:
  416.         print (Fore.YELLOW+"[!] Nesta parte er permitido apenas valores inteiros"+Style.RESET_ALL)
  417.         sys.exit(0)
  418.     return Lista
  419.  
  420. def Controle(Lista):# gerencia a escolha de entrada de valores
  421.    
  422.     ListaRetorno = [0]*int(Lista[3])
  423.     if Lista[0] =='m'  and Lista[1] == 'i':
  424.         ListaRetorno = Entrada_m_Inteiro(Lista[3])
  425.     elif Lista[0] == 'm'  and Lista[1] == 'd':
  426.        ListaRetorno = Entrada_m_Decimal(Lista[3])
  427.     if Lista[0] =='a'  and Lista[1] == 'i':
  428.         ListaRetorno = Entrada_a_Inteiro(Lista[3])
  429.     elif Lista[0] == 'a'  and Lista[1] == 'd':
  430.         ListaRetorno = Entrada_a_Decimal(Lista[3])
  431.     if Lista[0] == 'l':
  432.         ListaRetorno = LerArquivo(Lista)
  433.        
  434.    
  435.     return ListaRetorno
  436.  
  437. def Status(Lista): # printa a escolha do usuario
  438.    
  439.     print (Back.GREEN+"[+] Tipo de entrada -> ",Lista[0]+Style.RESET_ALL)
  440.     print (Back.GREEN+"[+] Tipo de dados   -> ",Lista[1]+Style.RESET_ALL)
  441.     print (Back.GREEN+"[+] Formula         -> ",Lista[2]+Style.RESET_ALL)
  442.     print (Back.GREEN+"[+] Quantidade      -> ",Lista[3]+Style.RESET_ALL)
  443.    
  444.  
  445. def Erro_entrada(Lista): # verifica a ocorrencia de erros
  446.  
  447.     if Lista[0] != 'm' and Lista[0] !='a' and Lista[0] !='l':
  448.         return  Fore.RED+"[!] Um erro encontrado no tipo de entrada escolhido por voce!"+Style.RESET_ALL
  449.     if Lista[1] != 'i' and Lista[1] !='d':
  450.         return Fore.RED+"[!] Um erro encontrado no tipo de dados escolhido por voce!"+Style.RESET_ALL
  451.     if Lista[2] !='s' and Lista[2] !='a':
  452.         return Fore.RED+"[!] Um erro encontrado na formula escolhida!"+Style.RESET_ALL
  453.     if int(Lista[3]) <= 0 and Lista[0] =='l':
  454.         pass
  455.     elif int(Lista[3]) <=0 and Lista[0] != 'l':
  456.         return Fore.RED+"[!] A quantidade escolhida nao er valida!"+Style.RESET_ALL
  457.     return "[+] Nenhum erro encontrado!"
  458.  
  459. def Menu():# primeira entrada de dados
  460.  
  461.     quantidade = None
  462.     retorno = None
  463.     formula = None
  464.     tipo    = None
  465.     entrada = None
  466.  
  467.     print ("MENU")
  468.     try:
  469.         print ("escolha abaixo o tipo de entrada que deseja!")
  470.         print ("[m] MANUAL")
  471.         print ("[a] automatica aleatória")
  472.         print ("[l] ler arquivo .txt")
  473.         entrada = input(":>")
  474.  
  475.         print ("escolha abaixo o tipo de dado que deseja inserir")
  476.         print ("[i] inteiros")
  477.         print ("[d] decimal")
  478.         tipo = input(":>")
  479.  
  480.         print ("escolha abaixo a formula para calcular o valor de k")
  481.         print ("[s] STURGES")
  482.         print ("[a] ANSELMO")
  483.         formula = input(":>")
  484.         if entrada != 'l' and entrada != 'L':
  485.             print("digite abaixo a quantidade de dados que deseja inserir")
  486.             quantidade = int(input(":>"))
  487.         else:
  488.             quantidade = 0
  489.     except:
  490.         print (FORE.RED+"Voce digitou alguma coisa erra, execute novamente e tente nao errar!"+Style.RESET_ALL)
  491.         sys.exit(0)
  492.    
  493.    
  494.     if entrada.isupper():
  495.         entrada = entrada.lower()
  496.     if tipo.isupper():
  497.         tipo = tipo.lower()
  498.     if formula.isupper():
  499.         formula = formula.lower()
  500.    
  501.     retorno = [0]*4
  502.     retorno [0] = entrada
  503.     retorno [1] = tipo
  504.     retorno [2] = formula
  505.     retorno [3] = str(quantidade)
  506.    
  507.     return retorno
  508.  
  509. def main():
  510.     Lista = Menu()
  511.     print ("------------------------------------")
  512.     if "[+] Nenhum erro encontrado!" != Erro_entrada(Lista):
  513.         print (Fore.RED+ "Status Erro -> ",Erro_entrada(Lista))
  514.         sys.exit(0)
  515.     else:
  516.         Status(Lista)
  517.    
  518.  
  519.     Lista_ = Controle(Lista)
  520.  
  521.     print ("[+]Lista inserida")
  522.    
  523.     print(Back.GREEN+str(Lista_)+Style.RESET_ALL)
  524.    
  525.     Lista_Ordenada = Sort(Lista_)
  526.     print ("---------------------------")
  527.     print ("[+]Lista ordenada abaixo")
  528.     print (Back.GREEN+str(Lista_Ordenada)+Style.RESET_ALL)
  529.     print ("---------------------------")
  530.     ranger = Ranger(Lista_Ordenada)
  531.     print (Back.GREEN+"[+] Ranger    -> ",str(ranger)+Style.RESET_ALL)
  532.     K = ControleF(int(Lista[3]),Lista[2])
  533.     print (Back.GREEN+"[+] K         -> ",str(K)+Style.RESET_ALL)
  534.     H = Intervalor(ranger,K)
  535.     print (Back.GREEN+"[+] Intervalo -> ",str(H)+Style.RESET_ALL)
  536.     print ("   Classe           FI           FAC           FR           XI           XI*FI           XI²*FI")
  537.    
  538.     print (Back.YELLOW+"-----------------------------------------------------------------------------------------------------------"+Style.RESET_ALL)
  539.     ListaFi = Classes(H,Lista_Ordenada,K)
  540.     print (Back.YELLOW+"-----------------------------------------------------------------------------------------------------------"+Style.RESET_ALL)
  541.    
  542.     ListaXi=Xi(Lista_Ordenada,H,K)
  543.     ListaXI2=Xi_2(ListaXi)
  544.     ListaXiFi  = XIxFI(ListaFi,ListaXi)
  545.     ListaXi2Fi =XI2FI(ListaXI2,ListaFi)
  546.     somatorioXiFi = SomatorioXiFi(ListaXiFi)
  547.     somatorioXi2Fi = SomatorioXi2Fi(ListaXi2Fi)
  548.     desvioPadrao = DesvioPadrao(somatorioXi2Fi,somatorioXiFi,int(Lista[3]))
  549.     variancia = Variancia(desvioPadrao)
  550.     media = Media(somatorioXiFi,int(Lista[3]))
  551.     cv = round((desvioPadrao/media)*100,1)
  552.    
  553.    
  554.     print (Back.GREEN+"Somatorio XixFi -> ",str(somatorioXiFi)+Style.RESET_ALL)
  555.     print (Back.YELLOW+"----------------------------#"+Style.RESET_ALL)
  556.  
  557.     print (Back.GREEN+"Somatario Xi2Fi -> ",str(somatorioXi2Fi)+Style.RESET_ALL)
  558.     print (Back.YELLOW+"----------------------------#"+Style.RESET_ALL)
  559.  
  560.     print (Back.GREEN+"Media                   -> ",str(media)+Style.RESET_ALL)
  561.     print (Back.YELLOW+"----------------------------#"+Style.RESET_ALL)
  562.  
  563.     print (Back.GREEN+"Desvio Padrao           -> ",str(desvioPadrao)+Style.RESET_ALL)
  564.     print (Back.YELLOW+"----------------------------#"+Style.RESET_ALL)
  565.  
  566.     print (Back.GREEN+"Variancia               -> ",str(variancia)+Style.RESET_ALL)
  567.     print (Back.YELLOW+"----------------------------#"+Style.RESET_ALL)
  568.     print (Back.GREEN+"Coeficiente de variação -> ",str(cv),"%"+Style.RESET_ALL)
  569.     print (Back.GREEN+"Quartil 1       -> ",str(Qi(H))+Style.RESET_ALL)
  570.     print (Back.GREEN+"Quartil 2       -> ",str(Qii(H))+Style.RESET_ALL)
  571.     print (Back.GREEN+"Quartil 3       -> ",str(Q3(H))+Style.RESET_ALL)
  572.    
  573.    
  574. if __name__ == "__main__":
  575.     main()
Add Comment
Please, Sign In to add comment