Need Help in Scrambling! Thank you

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pazzi
    New Member
    • Sep 2008
    • 2

    Need Help in Scrambling! Thank you

    I would like to make a code in which I scramble the words in the middle of a sentence so the first and last letter remain the same.

    example: The gentleman gave his seat to the lady
    = The geltneamn gvae his saet to the lday

    please inform me how you do it, so I can understand how to do one.

    thank you!
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    random.shuffle and string slicing is ideal for this task.[code=Python]import random

    def scramble(w):
    mid = list(w[1:-1])
    random.shuffle( mid)
    return w[0]+''.join(mid)+w[-1][/code]Now all you need is another function to break apart the sentence by words, process each word, and rejoin. Example:[code=Python]s = 'Mr. Harvey was notorious for his tendency to engage in endless circumlocution when a simple, brief explanation would suffice.'
    print process(s)

    >>> Mr. Heavry was nrutooois for his tedcnney to eggnae in esldens citcuuirlmocon wehn a smlpie, beirf eltnioaaxpn wluod suffice.[/code]

    Comment

    • pazzi
      New Member
      • Sep 2008
      • 2

      #3
      Thank You very much!

      Comment

      • aberry
        New Member
        • Sep 2008
        • 10

        #4
        yes, it works fine...
        but be sure to strip comma, semicolon char with word...
        like in string
        str1= "authors responsible for the design, creation, and management "
        str1.split() will give
        ['authors', 'responsible', 'for', 'the', 'design,', 'creation,', 'and', 'management']

        so strip comma in string "creation," and then pass to function :)

        Comment

        • aberry
          New Member
          • Sep 2008
          • 10

          #5
          repeated entry .. not able to delete it....

          Comment

          Working...