Home > OS >  Uniform distribution of array data
Uniform distribution of array data

Time:10-16

I have an array [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], and I would like to translate it into a uniform position, what would be the output get: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]. The array is not always of such length and the numbers in it can be in different proportions to each other, so the question arises how to do it dynamically and not manually?

Need help

CodePudding user response:

I don't know if I get your question right. Is this code what you're looking for?

a = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]

for e,i in enumerate(a):                        #finding the place where pattern is changed
    if i!=a[0]:
        divier_idx = e
        break

result=[]
for i in zip(a[:divier_idx],a[divier_idx:]):    #grouping data into needed formation 
    (first,sec) = i
    result.append(first)
    result.append(sec)

print(result)
# the output: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

CodePudding user response:

This would work:

arr = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]
counters = {}
for element in arr:
    counters[element] = counters.get(element, 0)   1
frequences = {k:len(arr)/float(v) for (k,v) in counters.items()}

progress = {k:0.0 for (k,v) in counters.items()}
result = []

for upperBound in range(len(arr)):
    partial_result = {}
    for (k,frequence) in frequences.items():
        if(frequence * progress[k] < float(upperBound)   0.5):
            progress[k] = progress[k]   1
            partial_result[k] = frequence * progress[k] - float(upperBound)
    for (k,v) in sorted(partial_result.items(), key=lambda item: item[1]):
        result.append(k)

print(result)

First getting frequencies for each number, then going from 1 to len(arr) checking if accumulated frequency for each number is below this threshold, if so output this number and accumulate its frequency further.

CodePudding user response:

Solution:

my_list = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]

def make_uniform_list(the_list):
    my_set = list(set(the_list))
    size = len(the_list)/len(my_set)
    new_list = []
    for i in range(round(size)):
        new_list  = my_set
    return new_list

Examples:

ex_1 = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]
print(make_uniform_list(ex_1))
#  [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

ex_2 = [0, 1, 1, 0, 1, 1, 1, 0, 0, 1]
print(make_uniform_list(ex_2))
#  [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

ex_3 = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3]
print(make_uniform_list(ex_3))
# [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
  • Related