2

Python中查找等概率最大出现元素的索引

 7 months ago
source link: https://www.jdon.com/72446.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python中查找等概率最大出现元素的索引

在本教程中,我们学习如何使用 Python 查找等概率最大出现元素的索引。如果我们将输入设为 {1, 2, 5, 3, 4, 5, 6, 5, 7, 8, 5, 9},则 5 会被分四次获取。索引号 5 是 2、5、7 和 10。这里,我们给出了一个解决方案,它以相等的概率返回最大出现元素的索引。如果数组有两个最大的出现,则解决方案应考虑第一个最大的出现。

这里给出一个数组索引输入及其相应输出的示例。

输入:   
arr[] = [ 1 ,  2 ,  5 ,  3 ,  4 ,  5 ,  6 ,  5 ,  7 ,  8 ,  5 ,  9 ]  

输出:    

5是 频率最大的元素, 出现 在 第二个 索引处。   
或者  
5是 频率最大的元素, 出现 在 第 5 个 索引处。   
或者  
5是 频率最大的元素, 出现 在 第 7 个 索引处。   
或者  
5是 频率最大的元素, 出现 在 第 10 个 索引处。   

上述所有输出都有相同的概率。  

算法
在这里,我们学习使用 Python 查找等概率最大出现元素索引的算法。

  1. 首先定义函数findIndexOfMaxElement,有两个参数,分别是arr和n
  2. 然后,保留地图上所有输入元素的计数。
  3. 现在,我们创建一个 for 循环。
  4. 然后,遍历这张地图。
  5. 之后,我们需要找到哪个元素最先出现的时间最长。
  6. 然后,生成一个 1 之间的“n”个随机数,并统计图中出现次数最多的元素。
  7. 现在我们初始化数组输入 arr[]
  8. 最后,遍历输入。然后,它返回最大出现元素的索引值的第 n 次出现。

这里,我们给出Python中的程序代码,用于查找等概率出现最大的元素的索引。代码如下 :

# 使用 Python 以相等概率查找最大出现元素的索引  
# 导入随机库  ;
import random  

# 使用两个参数定义函数 findIndexOfMaxElement:arr 和 n  
#它从数组中随机查找最大出现元素的索引值;
def findIndexOfMaxElement(arr, n):  

在这里,使用 dict()   对地图进行了均衡化处理;
map = dict()  

# 现在在这里创建一个 for 循环  ;
for i in range(n):  
        if(arr in map):  
            map[arr] = map[arr] + 1  
        else:  
            map[arr] = 1  


max_element = -323567  
最大出现元素存储在这里  
# 最大出现元素的计数存储在这里  ;

max_so_far = -323567  

然后,遍历该地图,并在最长时间内找到哪个元素最先出现;
for p in map:  

if (map[p] > max_so_far):  
            max_so_far = map[p]  
            max_element = p  


这里,随机数 k 在 [1, max_so_far]   之间产生;
k = int( ((random.randrange(1, max_so_far, 2) % max_so_far) + 1))  
i = 0  
count = 0  
# 再次遍历数组,返回最大元素   第 k 次出现的索引;

while ( i < n ):  

if (arr == max_element):  
            count = count + 1  

# 此处打印最大元素   第 k 次出现的索引;
        if (count == k):  

print("5 is the element with maximum frequency, which is present at index: " , i )  
            break  
        i = i + 1  

初始化数组输入 arr[]  ;
arr = [1, 2, 5, 3, 4, 0, 5, 6, 5, 7, 8, 5, 9]  
# Find the length of the array and store it in n  
n = len(arr)  

findIndexOfMaxElement(arr, n)  

现在,我们在 Python 中编译上述代码,编译成功后运行它。输出结果如下
5 is the element with maximum frequency, which is present at index: 11

结论
在本教程中,我们将学习如何使用 Python 以等概率查找最大出现元素的索引。在这里,我们主要检查哪个元素在给定的映射中出现的时间最多,然后随机找出最大出现元素的索引值。我们还要学习这个程序的算法。根据这一算法,我们编写上述 Python 代码并分享其输出结果。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK