A
A
Asya2018-03-13 14:13:49
Python
Asya, 2018-03-13 14:13:49

How to do permutations with replacement in python?

Let's say I have the string 'ABC'
and I need to get this: In general, so that the missing value is replaced by - For now, it just turns out like this:
'ABC',2 --> 'AB-', 'A-C', '-BC'
combinations('ABC', 2) --> AB AC BC

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ruslan., 2018-03-13
@asyaevloeva

Something like this, but there are loops here:
import itertools as it
def comb(base_str, num):
comb_list = list(it.combinations(base_str, num))
result = []
for tmp_list in comb_list:
ind_base = 0
ind_comb = 0
full_list = []
while ind_comb < tmp_list.__len__():
while ind_base < base_str.__len__():
if ind_comb < tmp_list.__len__() and base_str[ind_base] == tmp_list[ind_comb]:
full_list.append(base_str[ind_base])
ind_base += 1
ind_comb += 1
else:
full_list.append('-')
ind_base += 1
result.append(full_list)
return result
print(comb('ABCDE', 3))
Result:

R
Roman Volodin, 2018-03-13
@cronk

string = "ABC"
for s in string[::-1]:
    print(string.replace(s, "-"))

Result
AB-
A-C
-BC

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question