Connecting Tech Pros Worldwide Forums | Help | Site Map

Need Help in Scrambling! Thank you

Newbie
 
Join Date: Sep 2008
Posts: 2
#1: Sep 29 '08
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's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,564
#2: Sep 29 '08

re: Need Help in Scrambling! Thank you


random.shuffle and string slicing is ideal for this task.
Expand|Select|Wrap|Line Numbers
  1. import random
  2.  
  3. def scramble(w):
  4.     mid = list(w[1:-1])
  5.     random.shuffle(mid)
  6.     return w[0]+''.join(mid)+w[-1]
Now all you need is another function to break apart the sentence by words, process each word, and rejoin. Example:
Expand|Select|Wrap|Line Numbers
  1. s = 'Mr. Harvey was notorious for his tendency to engage in endless circumlocution when a simple, brief explanation would suffice.'
  2. print process(s)
  3.  
  4. >>> Mr. Heavry was nrutooois for his tedcnney to eggnae in esldens citcuuirlmocon wehn a smlpie, beirf eltnioaaxpn wluod suffice.
Newbie
 
Join Date: Sep 2008
Posts: 2
#3: Sep 29 '08

re: Need Help in Scrambling! Thank you


Thank You very much!
Newbie
 
Join Date: Sep 2008
Posts: 10
#4: Oct 3 '08

re: Need Help in Scrambling! Thank you


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 :)
Newbie
 
Join Date: Sep 2008
Posts: 10
#5: Oct 3 '08

re: Need Help in Scrambling! Thank you


repeated entry .. not able to delete it....
Reply