0

I have been trying to iterate through an array.

below is the code.

x = ['lemon', 'tea', 'water', ]

def randomShuffle (arr,n):
    from random import choices
    newList=[]


    for item in arr:
        r=choices(arr, k=n)

        if r.count(item) <= 2:
            newList.append(item)

        return (newList)

i would like to know the logic for writing it please.

thank you all

1 Answer 1

1

Use a while loop: if every item is to appear twice, then teh resulting array should be twice the length of the input one.
And of course check not to add the same item more than twice in the result ;)

Choices return a list of size 1, so I use [0] to get the element

xx = ["a", "b", "c"]

def my_function(x):
    res = []
    while len(res) < len(x) * 2:
        c = choices(x)[0]
        if res.count(c) < 2:
            res.append(c)
    return res

my_function(xx)
> ['c', 'c', 'a', 'b', 'a', 'b']
my_function(xx)
> ['a', 'b', 'b', 'a', 'c', 'c']
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate. That is exactly what's needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.