データを歪めるために使用replace()
しています。すべてのインスタンスが置換される「高歪み」設定と、各インスタンスが置換される可能性が 50% の「低歪み」設定が必要です。例えば:
x = "aaaaaaaaaa"
x = x.replace("a", "b")
'bbbbbbbbbb'
x = "aaaaaaaaaa"
x = x.5050replace("a", "b")
'aabbabbaab'
書き直さずreplace()
に、どうすればこれを行うことができますか?
randomモジュールを使用します。
import random
x = ''.join(i if random.randint(0, 1) else 'b' for i in x)
x
このコードは、基本的にifの各文字を にrandom.randint
評価し0
、'b'
それ以外の場合はそのままにします。
あなたの文字列が複雑なもので'aacakedaaasa'
、sのみを置き換えたい場合は'a'
、これを試してください:
x = ''.join(i if i != 'a' or random.randint(0, 1) else 'b' for i in x)
これは、文字が not の場合は何もせず、そうである場合は、前の例のようにif returnsに'a'
置き換えます。'b'
random.randint
0
random.choiceを使用して、文字列の母集団とb
同じサイズの s の文字列から新しいリストを作成できます
>>> from random import sample
>>> x = "aaaaaaaaaa"
>>> ''.join(random.sample(x + "b"*len(x), len(x)))
'baabbbbbba'
これは with を使用して文字列を理解するよりも 2 倍高速です。random.randint
>>> stmt_ab = "''.join(random.sample(x + 'b'*len(x), len(x)))"
>>> stmt_v = "''.join(i if random.randint(0, 1) else 'b' for i in x)"
>>> import timeit
>>> t1_v = timeit.Timer(stmt_v,setup="from __main__ import x, random")
>>> t1_ab = timeit.Timer(stmt_ab,setup="from __main__ import x, random")
>>> t1_v.timeit(100000)
2.749679788532113
>>> t1_ab.timeit(100000)
1.3974490402988167
代わりに、正確に 50% の置換が必要な場合は、次を使用できます。random.shuffle
>>> x = "aaaaaaaaaa"
>>> x = list(x[:len(x)/2] + 'b'*(len(x) / 2))
>>> random.shuffle(x)
>>> x = ''.join(x)
>>> x
'bbbaabbaaa'
これは、パーセンテージを指定できるボラティリティの回答の変形です
def replace_ramd(input_string, pct):
for r in range(len(input_string)):
yield input_string[r] if random.randint(0,100) > pct else chr(random.randint(64,127))