## itertools(pemutations) in python

ankith26
Posts: 236
Joined: Mon Mar 25, 2019 11:08 am
Location: /home/pi/pythonprojects/test.py
Contact: Website

### itertools(pemutations) in python

Now, this post will cover some math along with python so bear with me.
I am using permutations from itertools module in python..
What this basically does is gives all possible ways of arranging n amount of objects in r slots.
if i were to enter 123, my output would be
123
132
213
231
312
321
This way of outputting applies to words also where all words are outputted in dictionary order.
Cat will give me
act
atc
cat
cta
tac
tca
Now here comes my problem,
If i put something like boss, it will give

Code: Select all

``````1) boss
2) boss
3) bsos
4) bsso
5) bsos
6) bsso
7) obss
8) obss
9) osbs
10) ossb
11) osbs
12) ossb
13) sbos
14) sbso
15) sobs
16) sosb
17) ssbo
18) ssob
19) sbos
20) sbso
21) sobs
22) sosb
23) ssbo
24) ssob
``````
by doing the math I expect 12 words , but i get 24.. This is because of the repeation of the 's' in my input word.
Is there any way to ignore repetations and get output to be 12
Closer scan of output will reveal that every word is repeated exactly twice and you can find a matching pair for every word, which i hope to cancel out
I sat thinking for 5 minutes on what to put here. Finally I put something like this.
Check out my github page @ https://github.com/ankith26

ghp
Posts: 1468
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

### Re: itertools(pemutations) in python

Writing the results into a set will remove 'duplicate' results.

Code: Select all

``````from itertools import permutations

res = set()
cnt = 0

for n in permutations("boss"):
print(cnt, n)
res.add(n)
cnt += 1

print( len(res), res)``````
Where 'duplicate' is a bit misleading. For the permutations, the two 's' are different symbols. So 'boss' and 'boss' look same but are different, as the sequence is first s/0/ s/1/, second s/1/ s/0/. Read s/0/ as 's index 0', s/1/ as 's index 1'

The set just sees the value of the items and treats s/0/ same as s/1/.

The number of permutations may be large. N different items yield N! results. So having all of them in a set needs much memory.

Return to “Python”