我的Ceasar Chiper计划遇到了麻烦。
这是我到目前为止所做的:
def enchiper(s,n):
'''
This function takes a string(s) and an integer(n) and
shifts the elements of s around the alphabet
'''
Alpha1 = 'abcdefghijklmnopqrstuvwxyz'
Alpha2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if 1 == len(s):
if 'a' <= s[0] <= 'z':
spot1 = myIndex(s[0],Alpha1)
x = spot1 + n
if 26 < x:
y = x - 26
return Alpha1[y]
else:
return Alpha1[x]
elif 'A' <= s[0] <= 'Z':
spot1 = myIndex(s[0],Alpha2)
x = spot1 + n
if 26 < x:
y = x - 26
return Alpha2[y]
else:
return Alpha2[x]
else:
return s[0]
else:
if 'a' <= s[0] <= 'z':
spot1 = myIndex(s[0],Alpha1)
y = spot1 + n
if 26 < y:
x = y - 26
return Alpha1[x] + enchiper(s[1:],n)
else:
return Alpha1[y] + enchiper(s[1:],n)
elif 'A' <= s[0] <= 'Z':
spot1 = myIndex(s[0],Alpha2)
y = spot1 + n
if 26 < y:
x = y - 26
return Alpha2[x] + enchiper(s[1:],n)
else:
return Alpha2[y] + enchiper(s[1:],n)
else:
return s[0] + enchiper(s[1:],n)
def myIndex(element, sequence):
''' returns the number of times that an element appears in a list
returns a random number from 0 to length of sequence if the element
does not appear in the list
Input: element is either an integer or string
sequence is a list of strings and integers
'''
if 0 == len(sequence):
return 0
elif sequence[0] == element:
return 0
else:
return 1 + myIndex(element, sequence[1:])
该程序运行良好,有时我输入的字符串给我一个#34;字符串索引超出范围&#34;。例如:
>>> enchiper('hello',15)
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
enchiper('hello',15)
File "/Users/spencerzanardi/Documents/hw3pr2.py", line 41, in enchiper
return Alpha1[y] + enchiper(s[1:],n)
File "/Users/spencerzanardi/Documents/hw3pr2.py", line 41, in enchiper
return Alpha1[y] + enchiper(s[1:],n)
File "/Users/spencerzanardi/Documents/hw3pr2.py", line 41, in enchiper
return Alpha1[y] + enchiper(s[1:],n)
IndexError: string index out of range
另外,我在我的程序中使用递归。我不允许使用循环
答案 0 :(得分:0)
当我在y
中打印Alpha1[y]
时,我弄清了你的程序,我得到了26个。确实Alpha1
(或者2)从0开始索引。尝试更改{{1}的所有出现次数1}}和if 26 < x:
if 26 < y:
和if 26 <= x:
,它应该有效。
修改强>
不是您的问题,但是当第一个if 26 <= y:
大于26时您的程序失败了,您应该考虑在函数开头使用模数。 (例如n
)
答案 1 :(得分:0)
问题是您正在使用索引26,而数组Alpha1
和Alpha2
的索引从0到25.在特定的调用enchiper('hello',15)
中,问题是字母l
位于第11位。当您添加15时,您将得到26个。然后,条件26 < y
将不得到满足,因此您将尝试返回Alpha1[26]
,不存在。如果您按something > 26
更改something >= 26
的每一次出现,那么您的代码就会工作。
答案 2 :(得分:0)
def encipher(s, n):
diff = ord('Z') - ord('A')
if len(s) == 1:
num = ord(s)
num += n % diff
if s.isupper():
if num > ord('Z'):
num -= diff
elif num < ord('A'):
num += diff
elif s.islower():
if num > ord('z'):
num -= diff
elif num < ord('a'):
num += diff
return chr(num)
return encipher(s[0], n) + encipher(s[1:], n)
答案 3 :(得分:0)
虽然这不是大写/小写(虽然快速上或下,但它会)
def encyp(string,shift):
Alpha1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
c=string[0]
pos=Alpha1.find(c)
pos=(pos+shift)%26
if len(string)==1:
return Alpha1[pos]
else:
return encyp(string[0], shift) + encyp(string[1:], shift)
你可以缩短它......