Python HAIL CAESAR (凯撒密码) 3
2015-06-16 23:05
627 查看
# 6.00x Problem Set 6
#
# Part 1 - HAIL CAESAR!
import string
import random
WORDLIST_FILENAME = "E:/python/2015-6-10/words.txt"
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
inFile = open(WORDLIST_FILENAME, 'r')
wordList = inFile.read().split()
print " ", len(wordList), "words loaded."
return wordList
def isWord(wordList, word):
"""
Determines if word is a valid word.
wordList: list of words in the dictionary.
word: a possible word.
returns True if word is in wordList.
Example:
>>> isWord(wordList, 'bat') returns
True
>>> isWord(wordList, 'asdf') returns
False
"""
word = word.lower()
word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"")
return word in wordList
def randomWord(wordList):
"""
Returns a random word.
wordList: list of words
returns: a word from wordList at random
"""
return random.choice(wordList)
def randomString(wordList, n):
"""
Returns a string containing n random words from wordList
wordList: list of words
returns: a string of random words separated by spaces.
"""
return " ".join([randomWord(wordList) for _ in range(n)])
def randomScrambled(wordList, n):
"""
Generates a test string by generating an n-word random string
and encrypting it with a sequence of random shifts.
wordList: list of words
n: number of random words to generate and scamble
returns: a scrambled string of n random words
NOTE:
This function will ONLY work once you have completed your
implementation of applyShifts!
"""
s = randomString(wordList, n) + " "
shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' ']
return applyShifts(s, shifts)[:-1]
def getStoryString():
"""
Returns a story in encrypted text.
"""
return open("story.txt", "r").read()
# (end of helper code)
# -----------------------------------
#
# Problem 1: Encryption
#
def buildCoder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation, numbers and spaces.
shift: 0 <= int < 26
returns: dict
"""
### TODO.
b = string.ascii_lowercase
a = string.ascii_uppercase
x = {}
y = {}
for z in range(len(a) - shift):
x[a[z]] = a[z + shift]
for z in range(len(a) - shift, len(a)):
x[a[z]] = a[z + shift - len(a)]
for z in range(len(b) - shift):
y[b[z]] = b[z + shift]
for z in range(len(b) - shift, len(b)):
y[b[z]] = b[z + shift - len(b)]
return dict(x, **y)
def applyCoder(text, coder):
"""
Applies the coder to the text. Returns the encoded text.
text: string
coder: dict with mappings of characters to shifted characters
returns: text after mapping coder chars to original text
"""
### TODO.
new = ""
for word in text:
if word in string.ascii_lowercase or word in string.ascii_uppercase:
new = new + coder[word]
else:
new = new + word
return new
def applyShift(text, shift):
"""
Given a text, returns a new text Caesar shifted by the given shift
offset. Lower case letters should remain lower case, upper case
letters should remain upper case, and all other punctuation should
stay as it is.
text: string to apply the shift to
shift: amount to shift the text (0 <= int < 26)
returns: text after being shifted by specified amount.
"""
### TODO.
### HINT: This is a wrapper function.
try:
return applyCoder(text, buildCoder(shift))
except:
return "0"
这个地方如果不用try 就一直返回TypeError, 很奇怪 一晚上没搞明白= =
105 x = {}
106 y = {}
--> 107 for z in range(26 - shift):
108 x[a[z]] = a[z + shift]
109 for z in range(len(a) - shift, len(a)):
TypeError: unsupported operand type(s) for -: 'int' and 'str'
一直没搞明白 先记录下来
#
# Part 1 - HAIL CAESAR!
import string
import random
WORDLIST_FILENAME = "E:/python/2015-6-10/words.txt"
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
inFile = open(WORDLIST_FILENAME, 'r')
wordList = inFile.read().split()
print " ", len(wordList), "words loaded."
return wordList
def isWord(wordList, word):
"""
Determines if word is a valid word.
wordList: list of words in the dictionary.
word: a possible word.
returns True if word is in wordList.
Example:
>>> isWord(wordList, 'bat') returns
True
>>> isWord(wordList, 'asdf') returns
False
"""
word = word.lower()
word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"")
return word in wordList
def randomWord(wordList):
"""
Returns a random word.
wordList: list of words
returns: a word from wordList at random
"""
return random.choice(wordList)
def randomString(wordList, n):
"""
Returns a string containing n random words from wordList
wordList: list of words
returns: a string of random words separated by spaces.
"""
return " ".join([randomWord(wordList) for _ in range(n)])
def randomScrambled(wordList, n):
"""
Generates a test string by generating an n-word random string
and encrypting it with a sequence of random shifts.
wordList: list of words
n: number of random words to generate and scamble
returns: a scrambled string of n random words
NOTE:
This function will ONLY work once you have completed your
implementation of applyShifts!
"""
s = randomString(wordList, n) + " "
shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' ']
return applyShifts(s, shifts)[:-1]
def getStoryString():
"""
Returns a story in encrypted text.
"""
return open("story.txt", "r").read()
# (end of helper code)
# -----------------------------------
#
# Problem 1: Encryption
#
def buildCoder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation, numbers and spaces.
shift: 0 <= int < 26
returns: dict
"""
### TODO.
b = string.ascii_lowercase
a = string.ascii_uppercase
x = {}
y = {}
for z in range(len(a) - shift):
x[a[z]] = a[z + shift]
for z in range(len(a) - shift, len(a)):
x[a[z]] = a[z + shift - len(a)]
for z in range(len(b) - shift):
y[b[z]] = b[z + shift]
for z in range(len(b) - shift, len(b)):
y[b[z]] = b[z + shift - len(b)]
return dict(x, **y)
def applyCoder(text, coder):
"""
Applies the coder to the text. Returns the encoded text.
text: string
coder: dict with mappings of characters to shifted characters
returns: text after mapping coder chars to original text
"""
### TODO.
new = ""
for word in text:
if word in string.ascii_lowercase or word in string.ascii_uppercase:
new = new + coder[word]
else:
new = new + word
return new
def applyShift(text, shift):
"""
Given a text, returns a new text Caesar shifted by the given shift
offset. Lower case letters should remain lower case, upper case
letters should remain upper case, and all other punctuation should
stay as it is.
text: string to apply the shift to
shift: amount to shift the text (0 <= int < 26)
returns: text after being shifted by specified amount.
"""
### TODO.
### HINT: This is a wrapper function.
try:
return applyCoder(text, buildCoder(shift))
except:
return "0"
这个地方如果不用try 就一直返回TypeError, 很奇怪 一晚上没搞明白= =
105 x = {}
106 y = {}
--> 107 for z in range(26 - shift):
108 x[a[z]] = a[z + shift]
109 for z in range(len(a) - shift, len(a)):
TypeError: unsupported operand type(s) for -: 'int' and 'str'
一直没搞明白 先记录下来
相关文章推荐
- 学习Python4(hashlib)
- python中根据list中字符串元素的某一位(几位数字)对list排序
- ipython与python的区别
- win7搭建Python开发环境(下篇--安装pip和ipython解释器)
- Scrapy迁移到生产服务器(aliyun)
- IPython,让Python显得友好十倍的外套——windows XP/Win7安装详解
- Mac配置Python开发环境并实现简单的字符串和整数拼接
- Python读写文件
- BlenderPython (一)介绍及安装
- Python-django安装
- ZH奶酪:Python 中缀表达式转换后缀表达式
- [Python基础]008.异常
- python 与 mysql 互操作
- 三种Python下载url并保存文件的代码
- Python open()用法
- 安装python及机器学习相关软件包
- 10款最好的Python IDE
- Python:使用cPickle储存器存储对象
- Python:简单的文件备份脚本
- Python:实现多态