如何用因子打乱一个单词?
我想用一个因素来打乱一个单词。因子越大,单词就会变得越乱。
例如,系数为 1.00 的单词“paragraphs”将变为“paaprahrgs”,系数为 0.50 的单词“paragraphs”将变为“paargarphs”。
应考虑与原始字母位置的距离和打乱字母的数量。
到目前为止,这是我的代码,它只会在没有因素的情况下进行混乱:
def Scramble(s):
return ''.join(random.sample(s, len(s)))
有什么想法吗?
PS这不是一项家庭作业 - 我正在尝试做这样的事情: http:// d24w6bsrhbeh9d.cloudfront.net/photo/190546_700b.jpg
I would like to scramble a word with a factor. The bigger the factor is, the more scrambled the word will become.
For example, the word "paragraphs" with factor of 1.00 would become "paaprahrgs", and it will become "paargarphs" with a factor of 0.50.
The distance from the original letter position and the number of scrambled letters should be taken into consideration.
This is my code so far, which only scrambles without a factor:
def Scramble(s):
return ''.join(random.sample(s, len(s)))
Any ideas?
P.S. This isn't an homework job - I'm trying to make something like this: http://d24w6bsrhbeh9d.cloudfront.net/photo/190546_700b.jpg
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(5)
它可以通过多种方式实现,但这是我的解决方案:
编写一个仅更改字母位置的函数:
def scramble(s):
s = list(s) #i think more easier, but it is absolutely performance loss
p = s.pop(random.randint(0, len(s)-1))
s.insert(random.randint(0, len(s)-1), p)
return "".join(s)
并编写一个多次应用于字符串的函数:
def scramble_factor(s, n):
for i in range(n):
s = scramble(s)
return s
现在我们可以使用它:
>>> s = "paragraph"
>>> scramble_factor(s, 0)
'paragraph'
>>> scramble_factor(s, 1)
'pgararaph'
>>> scramble_factor(s, 2)
'prahagrap'
>>> scramble_factor(s, 5)
'pgpaarrah'
>>> scramble_factor(s, 10)
'arpahprag'
当然函数可以组合或嵌套,但我认为很清楚。
编辑:
它不考虑距离,但打乱功能很容易被替换,只需交换相邻字母即可。这是一个:
def scramble(s):
if len(s)<=1:
return s
index = random.randint(0, len(s)-2)
return s[:index] + s[index + 1] + s[index] + s[index+2:]
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您可以将该因子用作字符串中的多个打乱字符。
由于该因子似乎介于 0 和 1 之间,因此您可以将该因子乘以字符串的长度。
如果您希望第一个和最后一个字符保留在原位,只需将它们分开并稍后添加即可。
You could use the factor as a number of shuffling chars in the string around.
As the factor seem's to be between 0 and 1, you can multiply the factor with the string's length.
If you want the first and the last characters to stay in place, simply split them and add them later on.