views:

37

answers:

2

this function will not give me an output when tested in python's IDLE:

import random

def scramble(string):

rlist = []

 while len(rlist) < len(string):

        n = random.randint(0, len(string) - 1)
        if rlist.count(string[n]) < string.count(string[n]):
            rlist += string[n]
    rstring = str(rlist)        
    return rstring 

scramble('sdfa')

I've spent a long time trying to figure out the problem, but the code seems good to me.

A: 

Correctly formatting this seems to solve the problem.

import random

def scramble(string):
   rlist = []
   while len(rlist) < len(string):
      n = random.randint(0, len(string) - 1)
      if rlist.count(string[n]) < string.count(string[n]):
         rlist += string[n]
   rstring = str(rlist)        
   return rstring
print(scramble('sdfa'))

In Python, indentation is just as important as good syntax :) By the way, as @Vincent Savard said, you did not print the result. In your scramble() you returned a string, but you did not do anything with said string.

irrelephant
His original post had no formatting at all, I wouldn't blame the problem on indentation. Someone edited it, he may have not indented it correctly.
Vincent Savard
A: 

A couple of notes:

Do not use string as the argument name, it could clash with the standard module string.

You probably do not want to return an str() of the list, which results in something like

>>> rlist = ['s', 'a', 'f', 'd']
>>> str(rlist)
>>> "['s', 'a', 'f', 'd']"

Instead, to get a scrambled string result, use str.join():

>>> rlist = ['s', 'a', 'f', 'd']
>>> ''.join(rlist)
'safd'
>>> 

The last 2 lines of scramble can be joined in a single return:

return str(rlist)

or

return ''.join(rlist)
gimel