Skip to content Skip to sidebar Skip to footer

How To Repeat An Operation On A List

I want to have a list of 4-letters, then I want to pick two elements of it randomly, merge them together, and add it as a new element to the original list. This way I make a new li

Solution 1:

Try this out

import random
aList = ['A','B','C','D']
for i in range(5): aList.append(''.join(random.sample(aList, num)))
print(aList)

Solution 2:

Mya be you can create a method :

importrandomnum=2
aList = ['A','B','C','D']
def randomizeList(list):
    newList = []
    newList+=random.sample(list, num)
    L = [''.join(newList[0:2])]+list
    return L

Now u call this method as many times as you want:

list = randomizeList(randomizeList(randomizeList(randomizeList(aList))))

or

list1 = randomizeList(aList)
list2 = randomizeList(list1)
list3 = randomizeList(list2)

and ......

Solution 3:

By creating a function:

import random

defrandMerge(l:list, count:int) -> list:"""Returns the input list expanded by a joined element consisting of
    count elements from itself (no repeats allowed)"""return l + [''.join(random.sample(l,k=count))]

and calling it repeatedly:

num = 2
aList = ['A','B','C','D']
newList = aList[:]
for _ in range(6):
    print(newList)
    newList = randMerge(newList,num)
print(newList)

Output:

['A', 'B', 'C', 'D']['A', 'B', 'C', 'D', 'DC']['A', 'B', 'C', 'D', 'DC', 'ADC']['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD']['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD', 'CDA']['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD', 'CDA', 'CDC']['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD', 'CDA', 'CDC', 'ADCCDC']

Solution 4:

Try this

import random
     def randomoperation():
         num = 2
         aList = ['A', 'B', 'C', 'D']
         newList = []
         newList += random.sample(aList, num)
         L = [''.join(newList[0:2])]+aList
         return L
     for i inrange(5):
         print randomoperation()

Post a Comment for "How To Repeat An Operation On A List"