views:

59

answers:

4

This is the problem:

Function Name: randomSentenceRedux

Parameters:

1.string – a string object to manipulate

Return Value:

A transformed string where the words from the original sentence are in a random order.

Test Case(s):

>>>print randomSentenceRedux("My name is Sally Sue") 
My is name Sue Sally 
>>>print randomSentenceRedux("hello") 
hello
>>>print randomSentenceRedux("Don't scream at me!") 
Don't at scream me! 
>>>

Description: Write a function to randomize the order of the words in the input string string and return the resulting string. You may assume words are separated by a single space. You MAY NOT use the shuffle function found in python's random module

+1  A: 

Not sure how the Python syntax would fit, but using Java, you would tokenize the String on the space delimiter, then use a random index less than the length of the token array, and access that element of the token array, pop it, print it, and repeat until the token array was empty.

Andy
+1  A: 

It's a really simple algorithm:

  • Split the Sentence at every space (don't know about jython but both java and python have built-in functions for that)
  • Shuffle the Array
  • Join the resulting string array
  • Print the new string

For which part do you need help exactly?

UPDATE

Algorithm for shuffling

  • Create a new (empty) Array
  • While there are items in the old Array
  • Take a random Number between 0 and the Number of Items in the old Array -1
  • Remove the item from the old array and push it to the end of the new array
  • Repeat until there are no more items in the old Array

There are more advanced and definatly more efficient shuffling algorithms but this simple algorithm should get you started.

dbemerlin
I think he was looking for explicit alternative algorithm to using shuffle.
Andy
Sorry, the part I need help with is the randomizing part. Im not allowed to use a shuffle function and I do not know what to use besides that.
carson
@carson: Try googling for "shuffle algorithm" or so.
Daenyth
+1  A: 

Regarding shuffling - one idea is to go over the list of items (for i in range(len(lst))) and for each element at position i, swap it with random element (say at position randrange(len(lst)) )

Regarding swapping two variables, remember in Python you can do a,b = b,a and that works - instead of temp=a; a=b; b=temp you have to do in other languages.

Regarding separating the words, it's as easy as strVar.split() and re-assembling as easy as ' '.join(lst).

I am not including the exact code, since this being a homework you are expected to do the work... but with above in mind should be easy, no?

Nas Banov
+2  A: 

You should look at Wikipedia's article on the Fisher-Yates shuffle. It's efficient and simple. Here's the psuedo-code they give:

To shuffle an array a of n elements:
for i from n - 1 downto 1 do
     j ← random integer with 0 ≤ j ≤ i
     exchange a[j] and a[i]

It should be easy enough to convert to Python.

Brendan Long