In: Computer Science
In this problem you will need to read about the functions numpy.load and numpy.bincount. Store all answers in appropriate variables. numbers = np.load('randomints.npy')
Use only numpy functionality to carry out this part.
(a) Load the file randomints.npy into a numpy array. There are 100000 integers in this file and they are between 0 and 1000.
(b) Get a bincount array for the array loaded in the first part.
(c) Let M be the largest number of times an element occurs in the array.
What is the smallest number that occurs M times?
(d) What is the number of integers that occurred 111 times?
Solution: It has been assumed that the 'randomints.npy' file already exist. In case it does not exist and you would like to create the same, please run the following Code 1 one time only. (Please do not run this one time code if the file already exists)
Hope that helps.
Code 1 (one time code)
import numpy as np
import random
#Empty list
lst_int = []
#Add 100000 random numbers to the list
for i in range(100000):
lst_int.append(random.randint(0,1000))
# converting list to array
arr = np.array(lst_int)
np.save('randomints.npy',arr)
Main Solution to the various points have been given below :
The code has been tested it on a file with 10 random integers. The output has been given for the same. The code will work for 100000 random integers without any amendments.
#import
import numpy as np
# Problem Part a
# Load the file contents to an arrary b
b = np.load('randomints.npy')
#Print the array
print("Array from the file")
print (b)
#Get the corresponding bin_count array
print("Bin Count Array")
b_bit = np.bincount(b)
#Print the bin count array
print(b_bit)
#Maximum number of times an integer occurs M
#This can be found from the bincount array which stores occurances
M = np.max(b_bit)
#Print value of M for reference
print(f"Maximum Number of times: {M}")
#Enumerate the Bin Count array
#Break on the first index
#This will give the minimum number which occur
#Variable min_M will hold the value
for idx, x in np.ndenumerate(b_bit):
if x == M:
number = idx
min_M = number[0]
break
print(F"Minimum number which occurs Maximum times: {min_M}")
#Find number of integers which occured 111 times
#We will store this sum in OCC_111 variable
OCC_111 = 0
for idx, x in np.ndenumerate(b_bit):
if x == 111:
OCC_111 = OCC_111 + 1
print (f"Number of integers which occur 111 times : {OCC_111}")
Output
Array from the file
[10 3 10 3 6 2 5 3 5 5]
Bin Count Array
[0 0 1 3 0 3 1 0 0 0 2]
Maximum Number of times: 3
Minimum number which occurs Maximum times: 3
Number of integers which occur 111 times : 0