我尝试使用Caesar Code
创建将字符串编码为不同字符串的程序def encode(letters,code,word):
lettersTab = list(letters)
lettersTab = lettersTab*2
lenghtLetters = len(letters)
howMany = code%lenghtLetters
wordTab = list(word)
secondTab = [None]*len(word)
for j in range(0,len(word)):
for i in range(0,int(len(lettersTab)/2)):
secondTab[j] = wordTab[j].replace(lettersTab[i],lettersTab[i+howMany])
print(secondTab)
encode("bca",2,"abc")
该输入意味着b转换为a等,b-> a,c-> b,a-> c
输出应为:
['c','a','b']
但它是
['b','b','c']
答案 0 :(得分:0)
由于内循环
,您的算法无法达到预期效果 for i in range(0,int(len(lettersTab)/2)):
正在循环的每一步设置secondTab[j]
到wordTab[j]
,即使wordTab[j]
与lettersTab[i]
不匹配,这也不是您想要的。
请注意,如果newstr = oldstr.replace(a, b)
不包含newstr
,则oldstr
会oldstr
= a
。
所以这里是你的功能的清理版本,加上几个渐进式改进,最后的例子使用列表理解。我的一些版本使用index()
,如果它找不到它正在寻找的东西会抛出异常,但是你的原始代码会遇到类似的问题。
我更改了函数的名称,因为encode
是Python 2中的标准字符串函数(我正在运行)。
#! /usr/bin/env python
'''
Caeser encryption
From http://stackoverflow.com/questions/25950099/my-program-dont-work-i-dont-know-why
'''
import sys
def caeser_encode0(letters, code, word):
lettersTab = list(letters) * 2
howMany = code % len(letters)
wordTab = list(word)
secondTab = [None] * len(word)
for j in range(0, len(word)):
for i in range(0, int(len(lettersTab)/2)):
if wordTab[j] == lettersTab[i]:
secondTab[j] = wordTab[j].replace(lettersTab[i], lettersTab[i + howMany])
print(wordTab[j], lettersTab[i], lettersTab[i + howMany], secondTab)
print(secondTab)
def caeser_encode1(letters, code, word):
lettersTab = list(letters) * 2
howMany = code % len(letters)
wordTab = list(word)
secondTab = []
for ch in word:
for i in range(0, int(len(lettersTab)/2)):
if ch == lettersTab[i]:
secondTab.append(lettersTab[i + howMany])
print(ch, lettersTab[i], lettersTab[i + howMany], secondTab)
print(secondTab)
def caeser_encode2(letters, code, word):
lettersTab = list(letters) * 2
howMany = code % len(letters)
secondTab = []
for ch in word:
i = lettersTab.index(ch)
secondTab.append(lettersTab[i + howMany])
print(ch, lettersTab[i], lettersTab[i + howMany], secondTab)
print(secondTab)
def caeser_encode3(letters, code, word):
howMany = code % len(letters)
secondTab = []
for ch in word:
i = letters.index(ch)
newi = (i + howMany) % len(letters)
secondTab.append(letters[newi])
print(ch, letters[i], letters[newi], secondTab)
print(secondTab)
def caeser_encode4(letters, code, word):
howMany = code % len(letters)
secondTab = []
for ch in word:
newi = (letters.index(ch) + howMany) % len(letters)
secondTab.append(letters[newi])
print(ch, letters[newi], secondTab)
print(secondTab)
def caeser_encode(letters, code, word):
howMany = code % len(letters)
secondTab = [
letters[(letters.index(ch) + howMany) % len(letters)] for ch in word]
print(secondTab)
def main():
caeser_encode("bca", 2, "abc")
if __name__ == '__main__':
main()
希望您(或某人:))将从这些示例中了解有关Python的更多信息......