Skip to content

Commit ad61342

Browse files
committed
Implemented random_permutation() in place of shuffle() and adding docstring for the same.
random_permutation() utilizes permutation() of numpy and return a sequence.
1 parent 3282b7d commit ad61342

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
@@ meta
2+
name = random_permutation()
3+
type = method
4+
category = math
5+
subcategory = random
6+
7+
@@ signatures
8+
random_permutation(seq: Sequence[Any] -> Sequence[Any]
9+
10+
@@ variables
11+
seq: Sequence[Any] - Sequence of objects for which random permutation is required.
12+
13+
@@ description
14+
Generates a random permutation for the given sequence. Each time the `random_permutation()` is called, it generates and return a random permuted sequence of the given sequence.
15+
16+
The returned value will always be a sequence such as a list. If the provided sequence is empty, an empty list will be returned.
17+
18+
This function's randomness can be influenced by [](sketch_random_seed), and makes calls to numpy to select the random permutation.
19+
20+
@@ example
21+
def setup():
22+
words = ["apple", "bear", "cat", "dog"]
23+
perm = py5.random_permutation(words)
24+
py5.println(perm) # Prints one of the permutation of words.

py5_resources/py5_module/py5/mixins/math.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
import types
2424
import warnings
2525
from pathlib import Path
26-
from typing import Any, Union, overload
26+
from typing import Any, Union, overload, Sequence
2727

2828
import numpy as np
2929
import numpy.typing as npt
@@ -352,9 +352,17 @@ def random_sample(
352352
else:
353353
return []
354354

355-
def shuffle(self, objects: list[Any]) -> list[Any]:
356-
"""$class_Sketch_shuffle"""
357-
return self.random_sample(objects, len(objects), False)
355+
def random_permutation(self, seq: Sequence[Any]) -> Sequence[Any]:
356+
"""$class_Sketch_random_permutation"""
357+
if isinstance(seq, types.GeneratorType):
358+
seq = list(seq)
359+
indices = self._rng.permutation(range(len(seq)))
360+
if not isinstance(seq, list):
361+
try:
362+
return seq[indices]
363+
except:
364+
pass
365+
return [seq[idx] for idx in indices]
358366

359367
@overload
360368
def random_gaussian(self) -> float:

0 commit comments

Comments
 (0)