打乱功能不会输出

发布于 2024-09-30 12:04:38 字数 400 浏览 8 评论 0 原文

在 python 的 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')

我花了很长时间试图找出问题,但代码对我来说似乎很好。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北恋 2024-10-07 12:04:38

正确格式化这似乎可以解决问题。

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

在 Python 中,缩进与良好的语法一样重要:)
顺便说一句,正如 @Vincent Savard 所说,您没有打印结果。在 scramble() 中,您返回了一个字符串,但您没有对所述字符串执行任何操作。

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.

岁月蹉跎了容颜 2024-10-07 12:04:38

一些注意事项:

不要使用 string 作为参数名称,它可能与 标准模块字符串

您可能不想返回列表的 str() ,这会导致类似的结果

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

相反,要获取加扰的字符串结果,请使用 str.join()

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

最后两行scramble可以是加入单个返回

return str(rlist)

return ''.join(rlist)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文