如何在Python的随机数数组中找到最多和最少的猜测数?

时间:2018-10-18 19:25:35

标签: python arrays jython

我只需要在python的随机数数组中找到最多和最少的猜测数即可。到目前为止,这是我的代码:

import time
import random
random.seed()

def breakPIN(num):
  end = 0
  list = []
  for i in range(0,9999):
    list.append(random.randint(0,9999))
  printNow(list)  
  if (num == 4):
    end =9999
  elif (num == 6):
    end=999999
  p2b=random.randint(0,9999)

  time1=time.time()

  num=random.randint(0,end)
  while (num!=p2b):
    num=random.randint(0,end)
  list[num]=list[num]+1
  time2=time.time()
  lowest=list[i]
  for i in range(0,len(list)):
    if(lowest > list[i]):
      lowest=list[i]
  printNow(lowest)
  highest=list[i]
  for i in range(0,len(list)):
    if(highest<list[i]):
      highest=list[i]
  printNow(highest)
  return time2-time1


times=[]
for i in range(0,10):
  times.append(breakPIN(6))

sum=0
for i in range(0,len(times)):
  sum = sum + times[i]
printNow(sum/len(times))
printNow(times)

您可以告诉我,我已经找到了猜中的最大数字和最小数字。任何有关如何找到最多和最少猜出的数字的指针将不胜感激。

2 个答案:

答案 0 :(得分:0)

要查找最多和最少的数字,可以使用Counter

import random
from collections import Counter


def most_least_guessed(elements):
    counts = Counter(elements)

    most_guessed, _ = counts.most_common(1)[0]
    least_guessed, _ = counts.most_common()[-1]

    return most_guessed, least_guessed


random.seed(42)
lst = []
for i in range(0, 9999):
    lst.append(random.randint(0, 9999))

most, least = most_least_guessed(lst)

print(most, least)

输出

1106 9998

答案 1 :(得分:0)

要确定最多和最少的猜数字,您需要知道每个数字被猜了多少次。一旦知道每个人被猜了多少次,您就可以找到最小值和最大值。

要记录每个数字的猜测次数,您需要一个与可用数字计数长度相同的数组。

这称为直方图。