First script, please comment and advise

Just just at xs4all.nl
Thu Mar 9 09:32:31 EST 2006


In article <slrne10bpc.9pj.hexkid at ID-203069.user.individual.net>,
 Pedro Graca <hexkid at dodgeit.com> wrote:

> I'm sure this isn't very pythonic; comments and advice appreciated
> 
> 
>     def curious(text):
>         """ Return the words in input text scrambled except for the first and 
>         last letter. """
>         new_text = ""
>         word = ""
>         for ch in text:
>             if ch in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
>                 word = word + ch
>             else:
>                 new_text = new_text + scramble(word)
>                 word = ""
>                 new_text = new_text + ch
>         return new_text
>     
>     def scramble(word):
>         """ scramble word """
>         from random import randint
>     
>         if len(word) < 4:
>             return word
>         new_word = word[0]
>     
>         ### transform "curious" into ['u', 'r', 'i', 'o', 'u']
>         letters = []
>         for ch in word:
>             letters.append(ch)
>         del letters[0:1]
>         del letters[-1]
>     
>         ### why doesn't range(len(letters) - 1, 0, -1) work?
>         for i in range(len(letters) - 1, -1, -1):
>             j = randint(0, i)
>             new_word = new_word + letters[j]
>             del letters[j]
>         return new_word + word[-1]
>     
>     print curious(curious.__doc__)

    def curious(text):
        """ Return the words in input text scrambled except for the
        first and last letter. """
        new_text = ""
        word = ""
        for ch in text:
            if ch.isalpha():
                word += ch
            else:
                new_text += scramble(word)
                word = ""
                new_text += ch
        new_text += scramble(word)
        return new_text

    def scramble(word):
        """ scramble word """
        from random import shuffle
        if len(word) < 4:
            return word
        letters = list(word[1:-1])
        shuffle(letters)
        return word[0] + "".join(letters) + word[-1]

Just



More information about the Python-list mailing list