1

I want to generate a list of length n which contains n random unique integers, ordered by numerical value and with a difference of no more than 10 between any two elements.

I wrote this function:

import random
def make_list(n):
  list = []
  num = 0
  for i in range(30):
    num = num + random.randint(1,10)
    list.append(num)
  return(list)

It works but it seems verbose and I feel like there should be a better, more concise way using list comprehensions or other.

blhsing
  • 91,368
  • 6
  • 71
  • 106
Dylan Boyd
  • 19
  • 1

4 Answers4

2

You could use a generator expression to generate the intervals, then call itertools.accumulate to calculate the running sums.

>>> from itertools import accumulate
>>> from random import randint

>>> list(accumulate(randint(1, 10) for _ in range(30)))
[4, 8, 12, 16, 20, 26, 31, 41, 49, 50, 58, 63, 72, 77, 81, 86, 88, 92, 101, 106, 109, 114, 116, 122, 123, 133, 143, 153, 159, 160]
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1
import random

def make_list(n):
  num = 0
  return [num := num + random.randint(1, 10) for _ in range(n)]

You can use := operator after Python3.8

https://stackoverflow.com/a/54514656/17560347

吴慈霆
  • 523
  • 2
  • 15
1

Using islice and accumulate from the itertools module:

import random
import itertools as it

def make_list(n):
    i = iter(lambda: random.randint(1, 10), None)
    return list(it.islice(it.accumulate(i), n))
kaya3
  • 47,440
  • 4
  • 68
  • 97
0

You can use random.choices with the desired n passed as the k argument:

import random
from itertools import accumulate

print(list(accumulate(random.choices(range(1, 11), k=5))))

Demo: https://replit.com/@blhsing/VerifiablePleasingSolidstatedrive

blhsing
  • 91,368
  • 6
  • 71
  • 106