在不使用random.shuffle()的情况下在Python中对字符串进行加扰

问题描述 投票:0回答:4

我试图在不使用random.shuffle()的情况下搜索字符串“string”,但是我的代码不断产生缺少和重复字符的输出,例如gtrgtg,gnrtnn等我不确定我做错了什么。

    import random
    s = "string"
    new_s=[]
    for c in s:
      if random.choice(s) not in new_s:
        new_s.append(random.choice(s))

    print(''.join(new_s))
python-3.x random
4个回答
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等字符串。请注意,如果原始字符串中有重复项,则无法使用此字符串。

上面的代码非常低效。假设这是出于学习目的,我只给出了修正。通常,如果要反复检查集合中是否存在某些内容,则该集合应该是集合或字典。


1
投票

random.choice从字符串s中选择一个随机字符,但不删除它 - 因此可以多次选择相同的字符,并且根本不选择某些字符。

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。 :)


1
投票

使用while,你可以循环通过s直到new_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
>>> 

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"))
© www.soinside.com 2019 - 2024. All rights reserved.