我最近做了一项任务,我的教授说明了它是不是100%正确,但我不确定如何解决这个问题。他对我的hw的回复是"尝试29或55的密钥。而不是使用ord,使用ALPHABET字符串中的字母索引。"现在我对编程很陌生,所以任何一条建议都会有所帮助。需要帮助找出要做的事情。
代码:
def circularShift(text, key):
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
text = text.upper()
shiftedTextSoFar =" "
for letter in text:
shifted = ord(letter) + key
if (shifted < 65):
shifted += 26
if (shifted > 90):
shifted -= 26
shiftedTextSoFar +=chr(shifted)
return shiftedTextSoFar
print (circularShift("MOLLOY", 3)) #SHOULD PRINT PROORB
print (circularShift("PROOB", - 3)) # SHOULD PRINT MOLLOY
答案 0 :(得分:0)
以下是代码的改进版本,使用index
建议:
def circularShift(text, key):
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
shiftedTextSoFar =" "
# you can also change text to upper during for/loop
for letter in text.upper():
# should do a try/except here really in case user input invalid text
# using string index to return index value
# using (key % len(ALPHABET)) will reduce key length of any 26's multiples
shifted = ALPHABET.index(letter) + (key % len(ALPHABET))
# if after adjusting shifted is out of index, reduce by 26 i.e len(ALPHABET)
if shifted > len(ALPHABET):
shifted -= len(ALPHABET)
# Python already has -ve index taken care, ie. ALPHABET[-1] = 'Z'
shiftedTextSoFar += ALPHABET[shifted]
return shiftedTextSoFar
print (circularShift("MOLLOY", 29)) #SHOULD PRINT PROORB
print (circularShift("PROOB", 55)) # SHOULD PRINT MOLLOY
PROORB
SURRE