Python - 在第一个和最后一个单词以外的单词中随机翻转 2 个字符



此代码翻转单词中除第一个和最后一个字符之外的所有字符。如何使它只随机翻转第一个和最后一个字符之外的两个字符?

例如:

computers
cmoputers
comupters
compuetrs

法典:

def scramble(word):
    result = word[0]
    if len(word) > 1:
        for i in range(len(word) - 2, 0, -1):
            result += word[i]
        result += word[len(word) - 1]
    return result

def main():
    print ("scrambled interesting python computers")
    print scramble("scrambled"),scramble("interesting"),scramble("python"), scramble("computers")
main()

这应该适用于翻转两个字母。如果单词的长度小于或等于 3,则无法翻转。在这种情况下,它只是返回单词。

from random import randint
def scramble(word):
    if len(word) <= 3:
        return word
    word = list(word)
    i = randint(1, len(word) - 2)
    word[i], word[i+1] = word[i+1], word[i]
    return "".join(word)

如果要切换两个随机字母,可以这样做:

from random import sample
def scramble(word):
    if len(word) <= 3:
        return word
    word = list(word)
    a, b = sample(range(1, len(word)-1), 2)
    word[a], word[b] = word[b], word[a]
    return "".join(word)

尝试查看此代码是否适合您:

import numpy as np
def switchtwo(word):
    ind1 = np.random.randint(1, len(word)-1)
    ind2 = np.random.randint(1, len(word)-1)
    l = list(word)
    l[ind1], l[ind2] = l[ind2], l[ind1]
    return "".join(l)

请注意,如果碰巧等于ind2,则此处可能没有开关ind1。如果这不是傻瓜,您应该检查这种情况。

以下仅使用标准库工作。此外,它始终从字符串内部选择 2 个不同的字符。

import random
def scramble2(word):
    indx = random.sample(range(1,len(word)-1), 2)
    string_list = list(word)
    for i in indx:
        string_list[i], string_list[-i+len(word)-1] = string_list[-i+len(word)-1], string_list[i]
    return "".join(string_list)

此外,您将需要处理 len(word) <= 3 的情况:在这种情况下,random.sample 方法将抛出 ValueError,因为没有足够的项目可供采样(它采样而不替换)。一种方法是在这些情况下返回单词。

def scramble2(word):
    try:
        indx = random.sample(range(1,len(word)-1), 2)
    except ValueError:
        return word
    string_list = list(word)
    for i in indx:
        string_list[i], string_list[-i+len(word)-1] = string_list[-i+len(word)-1], string_list[i]
    return "".join(string_list)

相关内容

最新更新