开发者

scramble function won't output

开发者 https://www.devze.com 2023-01-23 09:24 出处:网络
this function will not give me开发者_StackOverflow an output when tested in python\'s IDLE: import random

this function will not give me开发者_StackOverflow 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.


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.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号