shuffling a list with restrictions in Python

2024/10/15 9:25:03

I have a problem with randomizing a list with restrictions in Python (3). I have seen a few other questions relating to this, but none of them really seem to solve my problem. I'm a beginner, so any help is much appreciated!

I'm designing an experiment using two types of stimuli: shapes and colors (four of each). I need to generate permutations of all 16 combinations, which I have done with random.shuffle-function:

import random# letters are shapes, numbers are colors
x=["a1","a2","a3","a4","b1","b2","b3","b4","c1","c2","c3","c4","d1","d2","d3","d4"]random.shuffle(x)

So far so good. However, I want to avoid a shape (letter) or color (number) to appear two times in succession in my result (e.g. "a2" followed by "a4", or "c2" followed by "a2").

Is there a way to make such a restriction?
Thanks in advance!

Answer

One way to handle this might be to have two lists one of shapes and one of colors. Shuffle each list individually. Now intermix the two lists. Since each list was built randomly, the mixed list is random as well, but you do not have any two entries together.

Note that using zip, you will actually get sets of pairs which will enable you to handle your test by getting each pair from the result.

In this particular case each shape is a member of the list shapes while each color is a member of the list colors

shapes = ['a', 'b', 'c', 'd']
colors = ['1', '2', '3', '4']
zip(shapes, colors)
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]

This gives us each individual shuffle rather than generating all 16 possibilities at once and then shuffling them. This might enable you to generate your test better.

If you want to ensure that two sets of lists do not have the same color or shape in the same position as the previous group of four, then you can test for that after the shuffle against the previous setting.

testing = True
while testing:newcolors = colorsrandom.shuffle(newcolors)# perform the test that you want to make get testresult True or Falseif testresult:colors = newcolorstesting = False

This will keep shuffling until testresult becomes True and discard all invalid results from random.shuffle()

https://en.xdnf.cn/q/69304.html

Related Q&A

Django: Is it reasonable to use objects as dictionary keys?

Is it reasonable to use objects as keys to a dictionary in django? I have done so and it works. But I am wondering if this is best practice, or if it is going to make difficulties I dont foresee righ…

How do I now (since June 2022) send an email via Gmail using a Python script?

I had a Python script which did this. I had to enable something in the Gmail account. For maybe 3 years the script then ran like this: import smtplib, ssl ... subject = some subject message body = &quo…

Fast relational database for simple use with Python [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Event handling with Jython Swing

Im making a GUI by using Swing from Jython. Event handling seems to be particularly elegant from Jython, just setJButton("Push me", actionPerformed = nameOfFunctionToCall)However, trying same…

How Does Deque Work in Python

I am having trouble understanding how the deque works in the snippet of code below, while trying to recreate a queue and a stack in Python.Stack Example - Understoodstack = ["a", "b"…

When to use generator functions and when to use loops in Python

I am coming from a Matlab background and I am finding it difficult to get around the concept of generators in Python. Can someone please answer me the following:The difference between a generator funct…

Airflow - Disable heartbeat logs

My logs are getting completely flooded with useless messages for every heartbeat. [2019-11-27 21:32:47,890] {{logging_mixin.py:112}} INFO - [2019-11-27 21:32:47,889] {local_task_job.py:124} WARNING - T…

different validation in drf serializer per request method

Lets say i have a model like so:class MyModel(models.Model):first_field = models.CharField()second_field = models.CharField()and an API view like so:class MyModelDetailAPI(GenericAPIView):serializer_cl…

How to import r-packages in Python

Im a bit troubled with a simple thing. I was trying to install a package called hunspell, but I discovered it is originally an R package. I installed this version: https://anaconda.org/conda-forge/r-hu…

XPath predicate with sub-paths with lxml?

Im trying to understand and XPath that was sent to me for use with ACORD XML forms (common format in insurance). The XPath they sent me is (truncated for brevity):./PersApplicationInfo/InsuredOrPrinci…