varying degree of shuffling using random module python

I am using two architecture programs, with visual programming plugins (Grasshopper for Rhino and Dynamo for Revit – for those that know / are interested)

Grasshopper contains a function called ‘Jitter’ this will shuffle a list, however it has an input from 0.0 to 1.0 which controls the degree of shuffling – 0.0 results in no shuffling 1.0 produces a complete shuffle.

The second of the programs (Dynamo) does not contain this functionality. It contains a shuffle module (which contains a seed value) however it is a complete random shuffle.

Ultimately the goal is to produce a series of solid and glazed panels, but to produce a slight random effect (but avoiding large clumping of solid and glazed elements – hence I want a “light shuffle”)

I have written a code which will calculate the number of glazed(True) and solid(False) values required and then evenly distribute True and False values based on the number of items and percent specified.

I have checked out the random module reference however I’m not familiar with the various distributions as described.

Could someone help out or point me in the right direction if an existing function would achieve this.

(I have cheated slightly by adding True False alternately to make up the correct number of items within the list – list3 is the final list, list2 contains the repeated module of true falses)

Many thanks

import math
import random

percent = 30
items = 42

def remainder():
    remain = items % len(list2)

    remain -= 1

    while remain > 0 :
        remain -= 1

    return list3

#find module of repeating True and False values
list1 = ([True] + [False] * int((100/percent)-1))

#multiply this list to nearest multiple based on len(items)
list2 = list1 * int(items/(100/percent))

# make a copy of list2
list3 = list2[:]

#add alternating true and false to match len(list3) to len(items)

#an example of a completely shuffled list - which is not desired 
shuffled = random.sample(list3, k = len(list3))


Here is an approach based on this paper which proves a result about the mixing time needed to scramble a list by using swaps of adjacent items

from random import choice
from math import log

def jitter(items,percent):
    n = len(items)
    m = (n**2 * log(n))
    items = items[:]
    indices = list(range(n-1))
    for i in range(int(percent*m)):
        j = choice(indices)
        items[j],items[j+1] = items[j+1],items[j]
    return items

A test, each line showing the result of jitter with various percents being applied to the same list:

ls = list(('0'*20 + '1'*20)*2)

for i in range(11):
    p = i/10.0

Typical output:


I’m not sure how principled the above is, but it seems like a reasonable place to start.

Leave a Reply

Your email address will not be published. Required fields are marked *