【发布时间】:2012-01-10 13:16:26
【问题描述】:
我在 python 中寻找 partial shuffle 函数,而不是完整的 shuffle。
示例:“字符串”必须产生“stnrig”,但不能产生“nrsgit”
如果我可以定义必须重新排列的字符的特定“百分比”会更好。
目的是测试字符串比较算法。我想确定“洗牌的百分比”,超过这个百分比(我的)算法会将两个(洗牌的)字符串标记为完全不同的。
更新:
这是我的代码。欢迎改进!
import random
percent_to_shuffle = int(raw_input("Give the percent value to shuffle : "))
to_shuffle = list(raw_input("Give the string to be shuffled : "))
num_of_chars_to_shuffle = int((len(to_shuffle)*percent_to_shuffle)/100)
for i in range(0,num_of_chars_to_shuffle):
x=random.randint(0,(len(to_shuffle)-1))
y=random.randint(0,(len(to_shuffle)-1))
z=to_shuffle[x]
to_shuffle[x]=to_shuffle[y]
to_shuffle[y]=z
print ''.join(to_shuffle)
【问题讨论】:
-
洗牌代码的问题是,如果有一系列交换产生循环,那么你最终得到的洗牌字符可能比预期的要少......
-
是的,小字符串很有可能。我认为我的代码偏向于速度而不是准确性。
-
其他一些提示:为什么在循环结束时增加
i?它不应该有任何影响(我认为这是while版本的遗留物);使用元组解构而不是使用中间变量,交换在 Python 中更惯用。 -
是的,i=i+1 是不必要的。您能否详细说明“元组解构”?
-
当然,就像
a, b = b, a一样简单,例如你可以在@jsbueno 的答案中看到它...顺便说一句,确切的名称是“元组解包”docs.python.org/tutorial/…
标签: python string random shuffle