Python, arrays/vectors and dictionaries


Hi, I'm new to python and I don't know how it should be done:

1) I have a 2×6 matrix generated by random numbers, for example:

matriz = [11, 4,  50, 8,  9,  78]
         [10, 33, 44, 57, 80, 90]   

What I need to do is the following: when I draw a value in the range of line 2 [10, 33, 44 …] I must return its respective value of line 1, for example if the number drawn is 85, I must return the value 9 from line 1. If the value 38 came out in the draw, I must return the value 4 from line 1.

value from 10 to 32 of the second line corresponds to value 11 of line 1 value from 33 to 43 of the second line corresponds to value 4 of line 1 and so on, but the matrix is ​​generated can be 2×10, 2×30, etc.


import random

Pessoa = random.sample(range(1,25),10)
Nota   = random.sample(range(1,25),10)

tmp = sum(Nota)

# sorteando um valor

print('Numero sorteado: ', n_escolhido)

I did it using list instead of matrix but I stopped at this point because I can't make equivalence of the person list with the ranges of the notes.


Using the data from your example can be simple, remembering that this code will only work if the values ​​of the second row of the matrix are in ascending order.

I used Numpy to create a 2x6 array (the same array as your example), the logic of the algorithm is simple, create a loop and compare the atual column position of row 2 of the matrix and the position of the atual+1 column atual+1 , if your number is between the two values ​​print the corresponding column value of row 1

the code

import numpy as np

#criando array do exemplo
matriz = np.array([[11, 4,  50, 8,  9,  78],[10, 33, 44, 57, 80, 90]])

#entre 10 e 32 = 11
#entre 33 e 43 = 4
#entre 44 e 56 = 50
#entre 57 e 79 = 8
#entre 80 e 89 = 9
#entre 90 e inf = 78

#numero para testar o algoritmo ou pegar número randômico entre 10 e 90

#imprime qual número estamos usando

#anda na segunda linha da matriz comparando a posição atual com a próxima posição
for i in range(0, matriz[1:,].shape[1]-1):
    if (numero >= matriz[1,i]) and (numero < matriz[1,i+1]):

#o ultimo índice foi deixado de fora no loop, comparar agora        
if numero >= matriz[1,i+1]:
Scroll to Top