2017-10-21 107 views
0

我試圖通過ascii索引來搜索caesar cipher程序,該範圍> = 32和< = 126。當我到達最後一個打印輸出時,我得到一些字符不在這個範圍內。我已經嘗試了循環和while循環,但不斷收到錯誤。使用索引範圍搜索ascii

我很抱歉,如果我沒有發佈這個正確。這是我的第一篇文章。

感謝您的任何幫助。

def cipher(phrase,shift): 

     x = list(str(phrase)) 
     xx = ''.join(list(str(phrase))) 

     yy = [] 
     print(x) 
     for c in xx: 
      yy.append(chr(ord(c)+shift)) 

     return ''.join(yy) 

    print(cipher('ABCDE', 97 - 65)) 
    print(cipher('abcde', 65 - 97)) 
    print(cipher(' !\"#$', 95))  

和我的輸出是:

['A', 'B', 'C', 'D', 'E'] 
abcde 
['a', 'b', 'c', 'd', 'e'] 
ABCDE 
[' ', '!', '"', '#', '$'] 
+0

什麼是你指定'x'和'xx'行的目的是什麼?我不認爲你需要這些。你可以直接在'phrase'上迭代。 – 2017-10-21 22:01:17

+0

爲什麼最後一次打印的轉換是95? – utengr

+1

當你運行'print(cipher('!\「#$',95))'你會把所有的字符移到126以上。那麼你想要達到什麼效果? – gommb

回答

0

這應該工作(注意,我清理你的代碼了一下):

def cipher(phrase, shift): 

    x = list(str(phrase)) 
    yy = '' 
    print(x) 
    for c in phrase: 
     dec = ord(c) + shift 
     while dec < 32: 
      dec = 127 - (32 - dec) 
     while dec > 126: 
      dec = 31 + (dec - 126) 
     yy += (chr(dec)) 

    return yy 

print(cipher('ABCDE', 97 - 65)) 
print(cipher('abcde', 65 - 97)) 
print(cipher(' !\"#$', 95)) 

輸出是:

['A', 'B', 'C', 'D', 'E'] 
abcde 
['a', 'b', 'c', 'd', 'e'] 
ABCDE 
[' ', '!', '"', '#', '$'] 
!"#$ 
+0

感謝您的幫助,我真的很感激它,代碼編輯起作用 – Jasper

+0

這是不是就像在原代碼中執行'cipher('!「#$',0)'一樣? – 2017-10-21 22:27:38

+1

@Wyatt是的,但我認爲這只是一個測試,以確保它正確包裝。 – gommb

0

我很好奇尋找使用mo的解決方案dulo與不從0開始的範圍,所以這裏是這樣的:

def cipher(phrase, shift): 
    """Shift phrase; return original and shifted versions.""" 
    collector = [] 
    for c in phrase: 
     i = ord(c) 
     if i < 32 or i > 126: 
      raise ValueError('Char not in range [32, 126]: %s' % c) 
     # Shift into range [0, 95) 
     i -= 32 
     # Apply cipher shift 
     i += shift 
     # Push the shifted value back into [0, 95) if necessary 
     i %= 95 
     # Shift back into range [32, 126] 
     i += 32 
     # Convert to char 
     d = chr(i) 
     collector.append(d) 
    return phrase, ''.join(collector) 

print(cipher('ABCDE', 97 - 65)) 
# -> ('ABCDE', 'abcde') 
print(cipher('abcde', 65 - 97)) 
# -> ('abcde', 'ABCDE') 
print(cipher(' !"#$', 95)) 
# -> (' !"#$', ' !"#$')