2017-12-24 37 views

答えて

0

はこの試してみてください。

from random import randint 

def shuffle(sr): 
    n = len(sr) 
    s = list(sr) 
    for i in range(n): 
     cur, idx = s[i], randint(0, n - 1) 
     s[i], s[idx] = s[idx], cur 
    return ''.join(s) 

print(shuffle("hello")) 
1

random.choiceは、文字列sのうち、ランダムな文字をchosesが、それを削除しない - ので、同じ文字を複数回選択することが可能だし、いくつかのために文字はまったく選択されません。

import random 

s = 'string' 
new_s = [] 

# rather than choosing a character, chose an index, use it and slice it out 
while s: 
    i = random.randint(0, len(s)-1) 
    new_s.append(s[i]) 
    s = s[:i] + s[i+1:] 
print(''.join(new_s)) 

# this is more elegant with lists: 
s = list(s) 
while s: 
    i = random.randint(0, len(s)-1) 
    new_s.append(s.pop(i)) 
print(''.join(new_s)) 

いずれのオプションも効率的ではありません...効率を上げるには、random.shuffleを使用してください。 :)

2

プログラムは現在の状態で、ランダムに選択された文字が文字列内にあるかどうかをチェックします。そうであれば、ループを続ける以外は何もしません。また、変数にrandom.choice(s)を割り当てないため、チェックを行った後に別の文字が生成されます。

作業バージョンは次のようになります。

import random 
s = "string" 
new_s = [] 
for c in s: 
    char = random.choice(s) # assign it to a variable 
    while char in new_s: # until a new character comes, repeat the procedure 
     char = random.choice(s) 
    new_s.append(char) 

print(''.join(new_s)) 

これはngtsrigsrnit、などのような文字列を使用すると、元の文字列で重複している場合、これは動作しませんが生成されます。

上記のコードは非常に非効率的です。私はこれが学習目的であると仮定して訂正をしただけです。通常、何かがコレクション内にあるかどうかを繰り返し確認したい場合、そのコレクションはセットまたは辞書でなければなりません。

+0

あなたは正しいと思います。 –

1

whileを使用すると、new_sの長さがsの長さに一致し、結果の文字列に繰り返しのない文字が含まれるまで、sをループすることができます。

import random 

s = "string" 
new_s = '' # So you will not need ''.join() when you print this result 

while len(new_s) != len(s): 
    char = random.choice(s) 
    if char not in new_s: 
     new_s += char 

print(new_s) 

rntigs 
>>> 
関連する問題