[Tutor] Suggestions for more efficient and optimized coding technique,

Robert Berman bermanrl at cfl.rr.com
Thu Jan 8 16:49:10 CET 2009


Hi,

One of the challenges on the challenge you web page appropriately titled 
'Brute force' reads as follows:

"The password you have to guess is 'loner' . Try all combinations of 
lowercase letters until you guess it.  Try not to loop much for example, 
save all used combinations in an array so you don't repeat."

My code is as follows:

#!/usr/bin/env python

import random

def GetString():
    alphabet='abcdefghijklmnopqrstuvwxyz'
    return ''.join(random.sample(alphabet,5))   

def main():
    password='loner'
    errknt = 0
    control = True
    while control is True:
        if GetString() != password:
            errknt +=1
        else:
            print 'Password found in ',errknt,' tries.'
            control = False

           
if __name__ == '__main__': main()    

The code does work. I am looking for suggestions to learn more about 
both efficiency  and optimization of code.

Since the challenge revolves around the use of randomized retrieval, I'm 
not too sure how to optimize the process. The authors concept of using 
arrays seem a bit superfluous as I think it takes longer to add an item 
to a dictionary and retrieve an item from a dictionary than it does to 
do an if compare of two 5 character strings. So, I left that code out of 
the program entirely. If that was wrong, or there is a better way to 
avoid duplication, please point me in the right direction.

I think, perhaps, I could make it a tad more efficient if I changed 
'alphabet' from a string to a list as I remember reading  that lists are 
significantly faster to manipulate than are strings. Is that true and is 
it a viable change.

I realize my code looks like modified C++ structured code. I am trying 
to become more Python concise but I think that is  a matter of writing 
more and more python code.

All suggestions, ideas, critiques are most welcome.

Thank you,

Robert


More information about the Tutor mailing list