Home > Net >  Generate n lists of numbers between two numbers with python
Generate n lists of numbers between two numbers with python

Time:10-31

I have a tuple J = (inf, sup, n) and I want to generate n lists of numbers between inf and sup.

J = (-7, 9.5, 4)

The expected output should be like this:

[-7,-2.875], [-2.875,1.25], [1.25,5.375], [5.375,9.5]

Can someone help ?

Thanks in advance !

CodePudding user response:

If this is Ok use of numpy you can use numpy.linspace and get what you want like below:

>>> import numpy as np
>>> n = 4
>>> lst = list(np.linspace(-7, 9.5, num=n 1))
>>> list(zip(lst, lst[1:]))
[(-7.0, -2.875), (-2.875, 1.25), (1.25, 5.375), (5.375, 9.5)]

>>> list(map(list, zip(lst, lst[1:])))
[[-7.0, -2.875], [-2.875, 1.25], [1.25, 5.375], [5.375, 9.5]]

CodePudding user response:

Sorry but this platform is not for getting code solutions but for debugging or fixing issues in your code. It would help if you could mention what is it have you tried so far ?

However, here's a solution.

Your inputs are inf, n, sup.

If you notice, you list of n tuples in between inf and sup.

So the difference will be (sup-inf)/n

In the example you gave, it will be (9.5-(-7))/4 = 4.125.

So we will move from -7 to 9.5 by storing in each tuple, an initial value and a final value.

For 1st pair, initial value = -7 final value = -7 4.125 = -2.875

For 2nd pair, initial = -2.875 Final = -2.875 4.125 = 1.25

3rd pair, initial = 1.25 final = 1.25 4.125 = 5.375

4th pair initial = 5.375 final = 5.375 4.125 = 9.5

You may create a function that returns a list of these Pairs.

def getLists(inf, n, sup):
    output = []
    initial = inf
    final = sup
    continuous_difference = (sup-inf)/n

    while(initial != final):
        output.append([initial, initial   continuous_difference])
        initial  = continuous_difference
    
    return output

if __name__ == '__main__':
    print(getLists(-7, 4, 9.5))

CodePudding user response:

[[J[0]   i/J[2]*(J[1]-J[0]), J[0]   (i 1)/J[2]*(J[1]-J[0])] for i in range(J[2])]
  • Related