Ad
Algorithm To Create A Binary-like Pattern
I have two numbers: n
and sp
. I want to create a pattern of list elements with sp
elements that rotate like binary digits up to n
. To elaborate more on the second part, here is an example:
n = 2, sp = 3
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]
Similarly:
n = 3, sp = 3
[0, 0, 0]
[0, 0, 1]
[0, 0, 2]
[0, 1, 0]
[0, 2, 0]
[0, 1, 1]
[0, 1, 2]
[0, 2, 1]
[0, 2, 2]
[1, 0, 0]
[1, 0, 1]
[1, 0, 2]
[1, 1, 0]
[1, 2, 0]
[1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[1, 2, 2]
[2, 0, 0]
[2, 0, 1]
[2, 0, 2]
[2, 1, 0]
[2, 2, 0]
[2, 1, 1]
[2, 1, 2]
[2, 2, 1]
[2, 2, 2]
I wish to maintain the order that I have given in the examples, that is the LSB is assigned first, then the next bit, and so on...
I could not think of any tactic to solve such a problem. All I could figure out is to use sp
to create a temporary list of size sp
, for instance, if sp == 3
, the temp_list can be [0 0 0]
. Then we iterate in a manner so that we get the pattern.
There is no constraint on the complexity of the algorithm, although a shorter algorithm would be very great.
Ad
Answer
One simple way of doing it is:
def get_patterns(n, sp):
ans = []
def _get_patterns(so_far):
if len(so_far) == sp:
ans.append(so_far[:])
return
for i in range(n):
so_far.append(i)
_get_patterns(so_far)
so_far.pop()
_get_patterns([])
return ans
n = 3
sp = 3
assert get_patterns(n, sp) == sorted([
[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0],
[0, 2, 0], [0, 1, 1], [0, 1, 2], [0, 2, 1], [0, 2, 2],
[1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0],
[1, 2, 0], [1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2],
[2, 0, 0], [2, 0, 1], [2, 0, 2], [2, 1, 0],
[2, 2, 0], [2, 1, 1], [2, 1, 2], [2, 2, 1], [2, 2, 2],
])
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad