I want to write a function that get two integers. The integers indicate how many strings of either of the two chars appears in a string.
For example:
my_func(x,y): x amount of 'u' and y amount of 'r'.
my_func(2,3) is a string 'uurrr'
And the goal of the function is to write all the possible combinations of that string without changing the amount of x,y and every rearrangement is different:
Example:
my_func(1,1) will return: 'ru', 'ur'
my_func(1,2) will return: 'urr', 'rur', 'rru'
my_func(2,2) will return: 'uurr', 'ruru', 'rruu','urur', 'ruur', 'urru'
What I tried without covering all cases:
RIGHT = 'r'
UP = 'u'
def factorial(m):
if m>1:
return factorial(m-1)*m
else:
return 1
def binom(n,k):
return int(factorial(n)/(factorial(k)*factorial(n-k)))
def up_and_right(n, k, lst):
if n-k == 1 or n-k==-1 or n-k == 0 or n==1 or k==1:
num_of_ver = n k
else:
num_of_ver = binom(n k,2)
first_way_to_target = RIGHT*n UP*k
lst.append(first_way_to_target)
way_to_target = first_way_to_target
for i in range(num_of_ver-1):
for j in range(n k-1,0,-1):
if way_to_target[j]==UP and way_to_target[j-1]==RIGHT:
way_to_target = list(way_to_target)
way_to_target[j-1] = UP
way_to_target[j] = RIGHT
way_to_target = ''.join(way_to_target)
lst.append(way_to_target)
return lst
Thanks in advance!
CodePudding user response:
Use itertools.permutations
to get all the rearrangements, make a set
of them to eliminate duplicates (because e.g. swapping two r
s around counts as a separate permutation but doesn't change anything), and then join them back into strings because permutations
returns character tuples instead.
This demonstration at the REPL should give you enough to write your function:
>>> import itertools
>>> [''.join(p) for p in set(itertools.permutations('uurr'))]
['uurr', 'ruur', 'ruru', 'rruu', 'urur', 'urru']