除了第一个和最后一个字符外,我的函数随机翻转一个单词的2个字符。我想使用这个函数来编写另一个函数build_sentence(string)
,它使用我的函数翻转句子中每个单词的2个字符。函数build_sentence(string)
应该返回一个包含完整句子的字符串,其中每个单词的字母都被scrambled(word)
加扰。
例如:
I dn'ot gvie a dman for a man taht can olny sepll a wrod one way. (Mrak Taiwn)
import random
def scramble(word):
i = random.randint(1, len(word) - 2)
j = random.randint(1, len(word) - 3)
if j >= i:
j += 1
if j < i:
i, j = j, i
return word[:i] + word[j] + word[i + 1:j] + word[i] + word[j + 1:]
def main():
word = scramble(raw_input("Please enter a word: "))
print (word)
main()
答案 0 :(得分:1)
你试过了吗?
' '.join(scramble(word) for word in phrase.split(' '))
答案 1 :(得分:0)
假设您对当前的单词加扰功能感到满意(只需更改一小部分,因此对于包含3个或更少字母的单词不会出错):
import random
def Scramble(word):
if len(word) > 3:
i = random.randint(1, len(word) - 2)
j = random.randint(1, len(word) - 3)
if j >= i:
j += 1
if j < i:
i, j = j, i
return word[:i] + word[j] + word[i + 1:j] + word[i] + word[j + 1:]
else:
return word
def ScrambleSentence(sentence):
scrambledSentence = ""
for word in str.split(sentence):
print(scrambledSentence + "\n")
scrambledSentence += Scramble(word) + " "
return scrambledSentence.strip()
def main():
sentence = ScrambleSentence(input("Please enter a sentence: "))
print (sentence)
main()