python shuffle and print string and without reverse string

109 Views Asked by At

Let's say I have string, s='AADD'. I have used more_itertools and distinct permutation, which would print out (AADD,ADDA,DDAA,ADAD,DADA,DAAD).

My question is, because AADD and DDAA, ADAD and DADA are essentially mirror image of each other, I want to get rid of one of them, how should I revise my code to achieve this?

import more_itertools

s = 'AADD'
#counting = 0
for i in more_itertools.distinct_permutations(s):
    print(''.join(i))
    #counting += 1

Update: I have another question regards to large amount of data processing. Let's say my string "s" has 50 letters instead of 4, I wonder if the "distinct_permutation" from "more_itertools" is the most efficient way of doing it? I used Mathematica to calculate all the possible combinations, there are more than 10 billons possible combos, I wonder if there's a faster way of accomplishing this task. Apologizing in advance if this question is stupid, because I haven't taken any coding class and am learning coding myself at the same time while doing the project.

3

There are 3 best solutions below

1
On

You can utilize reversed() here:

import more_itertools

s = 'AADD'

options = [i for i in more_itertools.distinct_permutations(s)]

no_mirrors = []
for i in options:
    if tuple(reversed(i)) not in no_mirrors:
        no_mirrors.append(i)

for i in no_mirrors:
    print(''.join(i))

Output:

DDAA
DADA
ADDA
DAAD
0
On

A simple one-line solution without needing a temporary set or list, by taking advantage of the fact that the "greater than or equal to" operator works on sequences in python:

>>> from more_itertools import distinct_permutations
>>> [''.join(l) for l in distinct_permutations('AADD') if l >= l[::-1]]
['DDAA', 'DADA', 'ADDA', 'DAAD']
5
On

Here is a solution without using reverse / reversed. This works on the logic that for a given string w, w[::-1] would be the reversed string.

>>> import more_itertools
>>> s_list = list(map(''.join, more_itertools.distinct_permutations('AADD')))
>>> [w for w in s_list if w <= w[::-1]]
['ADDA', 'DAAD', 'ADAD', 'AADD']