Answer the question
In order to leave comments, you need to log in
How to get all combinations of elements of a string in a slice?
The code
import itertools
for i in itertools.product('ABC', repeat=3):
print(''.join(i))
Answer the question
In order to leave comments, you need to log in
You have the product of the string three times over itself. A string of length 3. Total 3**3 == 27 options.
Each element can be assigned a serial number.
for i in range(27):
print(f'{i:2}:', i // 9 % 3, i // 3 % 3, i % 3)
s = 'abc'
def g(i):
return s[i // 9 % 3], s[i // 3 % 3], s[i % 3]
for i in range(len(s) ** 3):
print(g(i))
def g(s, i):
n = len(s)
return [
s[i // n**(n-j-1) % n]
for j in range(n)
]
my_custom_string = 'abc'
for i in range(len(my_custom_string) ** len(my_custom_string)):
print(g(my_custom_string, i))
import itertools
import functools
import operator
class Producti:
def __init__(self, *iters, repeat=1):
iters = [list(it) for it in iters]
self.iters = iters * repeat
self._len = functools.reduce(operator.mul, map(len, self.iters))
def __len__(self):
return self._len
#def __iter__(self):
# return (self[i] for i in range(len(self)))
def __getitem__(self, idx):
if isinstance(idx, slice):
return (self[i] for i in range(len(self))[idx])
if idx >= len(self):
raise IndexError(f'product index out of range')
r = []
d = 1
for it in self.iters:
r.append(it[idx // d % len(it)])
d *= len(it)
return tuple(r[::-1])
for x in Producti('abc', repeat=3)[3:7]:
print(x)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question