Reputation: 71
I have this
>>> a = [1, 4, 7, 11, 17]
Is there any way to add 4 characters '-'
randomly between the other elements to achieve, for example
['-', 1, '-', 4, 7, '-', '-', 11, 17]
Upvotes: 4
Views: 7712
Reputation: 6185
Since performance is not an issue, the following is another solution to your issue (amended per @AChampion comment):
from __future__ import print_function
import random
_max = 4
in_list = [1, 4, 7, 11, 17]
out_list = list()
for d in in_list:
if _max:
if random.choice([True, False]):
out_list.append(d)
else:
out_list.extend(["-", d])
_max -= 1
else:
out_list.append(d)
# If not all 4 (-max) "-" have not been added, add the missing "-"s at random.
for m in range(_max):
place = random.randrange(len(out_list)+1)
out_list.insert(place, "-")
print(out_list)
Which gives:
$ for i in {1..15}; do python /tmp/tmp.py; done
[1, '-', 4, '-', '-', 7, 11, '-', 17]
['-', 1, 4, '-', '-', 7, 11, '-', 17]
['-', 1, 4, '-', 7, '-', 11, 17, '-']
[1, '-', 4, '-', '-', 7, '-', 11, 17]
[1, '-', 4, '-', '-', 7, 11, '-', 17]
['-', 1, 4, '-', 7, 11, '-', 17, '-']
['-', '-', 1, '-', 4, '-', 7, 11, 17]
[1, 4, '-', 7, '-', '-', '-', 11, 17]
['-', 1, 4, 7, '-', 11, '-', '-', 17]
[1, 4, '-', '-', '-', 7, '-', 11, 17]
['-', '-', 1, 4, 7, 11, '-', 17, '-']
['-', '-', 1, '-', 4, '-', 7, 11, 17]
['-', 1, '-', 4, '-', 7, 11, '-', 17]
[1, '-', 4, '-', 7, '-', 11, '-', 17]
[1, '-', '-', 4, '-', 7, 11, '-', 17]
Upvotes: 0
Reputation: 30258
You could randomly interleave the '-'
s using iterators and random.sample()
:
In [1]:
a = [1, 4, 7, 11, 17]
pop = [iter(a)]*len(a) + [iter('-'*4)]*4
[next(p) for p in random.sample(pop, k=len(pop))]
Out[1]:
['-', '-', 1, '-', 4, 7, 11, '-', 17]
Upvotes: 2
Reputation: 73460
You could simply do:
import random
for _ in range(4):
a.insert(random.randint(0, len(a)), '-')
The loop body inserts a '-'
at a random index between 0
and len(a)
(inclusive). However, since inserting into a list is O(N)
, you might be better off performance-wise constructing a new list depending on the number of inserts and the length of the list:
it = iter(a)
indeces = list(range(len(a) + 4))
dash_indeces = set(random.sample(indeces, 4)) # four random indeces from the available slots
a = ['-' if i in dash_indeces else next(it) for i in indeces]
Upvotes: 8
Reputation: 31
Python has insert(index, value) list method that will do the trick. What you want is:
import random
l = [1, 2, 3, 4]
for x in range(0, 4): # this line will ensure 4 element insertion
l.insert(random.randrange(0, len(l)-1), '-')
randrange() will generate random integers from within index range of your list. Thats it.
Upvotes: 2