[Tutor] Obtaining various combinations of a given word

Vivek Sant vsant at hcs.harvard.edu
Wed Jul 30 01:08:14 CEST 2008


Hi Sai krishna,

I recently wrote a program that does something similar to what you  
want. If you are familiar with the game text-twist, I wrote up a  
"solver" that will untwist any word by generating all possible  
combinations and then checking against a dictionary. To be honest, I  
had a little help from the internet for the permute function. Below  
is the code.

To address your question, when you find yourself doing something like  
if 1, ..., if 2, ... ..., if 3, ... ... ..., you probably want to use  
recursion, which is what my permute function uses below. The whole  
point of programming is to make the computer do all the repetition,  
not you, the programmer in copy and pasting and changing! Hope this  
helps!

Regards,
Vivek


#!/usr/bin/env python
import sys
import os
import commands
import random

if len(sys.argv) == 1:
   print "Usage: "+sys.argv[0]+" word [len]"
   exit()

word = sys.argv[1].lower()
if len(sys.argv) == 2:
   n = len(word)
else:
   n = int(sys.argv[2])

a = []
for i in range(len(word)):
   a.append(word[i])

def permute(seq):
   if len(seq) <= 1:
     yield seq
   else:
     for i in xrange(0,len(seq)):
       for tail in permute( seq[:i] + seq[i+1:] ):
         yield [ seq[i] ] + tail

# Load dict in memory
dict = {}
infile = open("wordlist.txt", "r")
for t in infile.readlines():
   dict[t.rstrip()] = 1

printed_words = []

for o in permute(a):
   possible_string = ''.join(o)
   possible_word = possible_string[:n]
   if dict.has_key(possible_word):
     if possible_word in printed_words:
       continue
     else:
       printed_words.append(possible_word)
       print possible_word



On Jul 29, 2008, at 5:50 PM, sai krishna wrote:

>
> Hi,everyone.
> My name is Sai krishna, and I'm new to Python as well as Programming.
>
> I wanted to print out all the combinations of a given word.
> I am doing it this way:
>
> n='cat'
> def arrange(n):
> if len(n)==1: #length of word is 1
>     print n
> elif len(n)==2: # length of word is 2
>     print n[0]+n[1]
>     print n[1]+n[0]
> elif len(n)==3:
>     print n[0]+n[1]+n[2]
>     print n[0]+n[2]+n[1]
>     print n[1]+n[0]+n[2]
>     print n[1]+n[2]+n[0]
>     print n[2]+n[0]+n[1]
>     print n[2]+n[1]+n[0]
>
> This process is quite lengthy, and I have managed to do this for  
> word containing 5 letters,i,e.,120 combinations
> Is there a better way?
> Please help.
>
> -- 
> cheers!!!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list