1

I want to generate a list of random numbers where the range and the length of the list can be varied later without modifying the function.So i thought of creating a function and the code i tried using python 3x is as follows:

class Traffic_matrix:

  def All_traffic(self,first,last,length):
      all_t=[]
      for i in range(length):
        all_t.append (random.randint(first, last))
all_t = Traffic_matrix()
print(all_t.All_traffic(23,56,6))

I know i have made a mistake somewhere and dont know what it is. Please help me out to sort this.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219

2 Answers2

1

You are essentially re-building (a worse version of) random.choices(...) with your function. Better use choices:

import random

class Traffic_Matrix:

  @classmethod
  def All_Traffic(cls,first,last,length):
      # return smth from it to get "results"
      return random.choices(range(first,last+1), k=length)

values = Traffic_Matrix.All_Traffic(23,56,6)
print(values)

It does not make much sense to put it into a class - no instance-members are used - you could define it as classmethod if you really need a "renamed" random.choices()

Output:

[25, 33, 42, 38, 38, 45]

Doku: random.choices(population, weights=None, *, cum_weights=None, k=1)

See: What is the difference between @staticmethod and @classmethod?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Thank you very much and it gives the expected result. But can you please explain the logic behind(last+1) and cls ? If i remove cls; it says that "All_traffic() takes 3 positional arguments, but 4 were given. What are the given 4? I have passed only 3 values (23,56,6). –  Sep 26 '18 at 16:42
  • 1
    @ShenuAmaya Read the SO question about @classmethods. The `cls` is autoprovided when you call the method, same as for instancemethods that get a `self` as first parameter autoprovided. `cls` would be "the class itself". `last+1` because the `range(1,100)` produces 1..99 - not to 100. `randint(1,100)` would produce from 1 to 100. See [range-doku](https://docs.python.org/3/library/functions.html#func-range) – Patrick Artner Sep 26 '18 at 17:30
  • 1
    @ShenuAmaya [classmethods](https://docs.python.org/3/library/functions.html?highlight=classmethod#classmethod) – Patrick Artner Sep 26 '18 at 17:34
0

you just add " return all_t " as last statement of your All_traffic function definition. It would work .