I have a string show the step going in m x n grid like this problem: https://leetcode.com/problems/unique-paths/
step = 'DDRR'
D mean go Down and R mean go to Right I want to show permutations without replacement, and i found the itertools built-in on Python.But it's say:
Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values.
So that when I using itertools.permutation(step,4), it's contain many replications.
>>> itertools.permutations(step,4)
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')
I want something like:
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('R', 'R', 'D', 'D')
I found some answer using set(itertools.permutations(step,4)), but because apply set() method, the itertools.permutation() method still calculate all possibilities. Is there anyway to avoid it, or is there any built-in function can do permutation without repetitions in Python?
itertools.permutations(step,4), maybe you meantstep = list('DDRR')DDDDDRRRRRthere are already 3.6 million permutations but only 252 different ones, so a reasonable method producing only the latter shouldn't have trouble being faster.Dsymbols and (n-1)R, or equivalently nRsymbols with (m-1) bars|between them. (You don't need to compute the actual combinations, and for m,n up to 100 that would be prohibitive). The number of ways is given by the well-known Stars-and-Bars formula