Sum indices of a vector respecting condition

Asked

Viewed 320 times

0

I have the following code:

import random

usuarios = 2
APs = 2
distancias = random.sample(range(0, 100), usuarios*APs)
teste = [sum(distancias[x: x + usuarios]) for x in range(0, len(distancias), usuarios)]

print(teste)

This code creates a vector with the size of the multiplication of the Aps with the users and then adds 2 to 2 and saves in the test vector..

For example:

  • Let’s say the vector is like this:

    distances = [10, 20, 40, 60]

  • The result will be like this:

    test = [30, 100]

However, what I wish is that the sum be made only of values less than 50, if greater, the value is attributed to the sum before or after..

For example:

In the above values the answer should be:

teste = [90, 40]
  • Note that the value 60 was added to the part previously added, because it is greater than 50.

I’m sorry if I wasn’t clear, I tried to be as clear as I could.

Anyone, can you help me with this problem? I can’t go on.

  • 1

    Even the part of adding two to two was clear, but the part of adding less than 50 was not. Why in the example was added 10, 20 and 60 and 40 not? The 40 is less than 50, so shouldn’t it be added together? In fact, what are you trying to solve? Try to describe the problem and not only the solution you tried, because maybe this is the best way out.

1 answer

0


I believe that the best thing for Voce would be to transform the array into a 2-dimensional array and then add the pairs together.

An example using numpy:

import random
import numpy as np

# tamanho de cada um dos novos arrays pequenos
usuarios = 2
# convertendo em um array do numpy
distancias = np.array([1,2,3,4,5,6,7,8,9,10])
print("distancias = ")
print(distancias)
# transformando o array de 10 valores em um array de 5 valores
# onde cada um desses valores eh um array com 2 valores
matrix = distancias.reshape((distancias.size // usuarios),usuarios)
print("matrix = ")
print(matrix)
# soma cada um desses arrays pequenos, 
# criando um array array das somas
nova = matrix.sum(axis=1)
print("nova = ")
print(nova) # [ 3  7 11 15 19]

You can see this example running here: https://repl.it/@thiagodamata/GiddyPettyAmurratsnake

Browser other questions tagged

You are not signed in. Login or sign up in order to post.