gpt4 book ai didi

java - 使用 Jython,我需要随机化一个字符串以保持单词完整

转载 作者:行者123 更新时间:2023-12-01 17:39:01 25 4
gpt4 key购买 nike

这就是问题:

函数名称:randomSentenceRedux

参数:

1.string – 要操作的字符串对象

返回值:

转换后的字符串,其中原始句子中的单词按随机顺序排列。

测试用例:

>>>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!
>>>

描述:编写一个函数来随机化输入字符串 string 中单词的顺序并返回结果字符串。您可能会假设单词之间由一个空格分隔。你不能使用 python random 模块中的 shuffle 函数

最佳答案

您应该查看维基百科关于 Fisher-Yates shuffle 的文章。它高效且简单。这是他们给出的伪代码:

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]

转换为 Python 应该很容易。

关于java - 使用 Jython,我需要随机化一个字符串以保持单词完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3249515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com