使这段代码看起来更优雅

时间:2015-04-07 06:43:13

标签: python encryption

我在Python和编程方面绝对是新的,我做了这个bifid cipher,我希望听到关于如何改进并让它看起来更优雅的意见,提前感谢。

我参加过Codecademy和Udacity的课程,而且我学到了很多东西。

import itertools


#Genera coodernadas-Generate Coordinates
coordinates = [[x,y] for x in range(1,6) for y in range(1,6)]

#Genera alfabeto-Generate Alphabet
alfa = []
for i in range(97,123):
    alfa.append(chr (i))
alfa.remove("i")

#Genera diccionario de coordenadas y alfabeto - Generate dictionary and coordinates alphabet 
alfacor = {}
alfacor = dict(zip(alfa,coordinates))


#Leer Txt - Read txt
document = open("Z:\\R\\Desktop\\BIFIDO\\easy.txt")
contenido = document.read()
print (contenido)
document.close()

#Encripta fase1 - Get's coordinates of txt
encripta = []
for e in contenido:
    encripta.append(alfacor[e])

#Unir lista encripta - Merge content of encropita in a new list
merged = list(itertools.chain.from_iterable(encripta))

#Divido lista merge en partes iguales - Divide meged list to get new coordinates
B = merged[:len(merged)/2]
C = merged[len(merged)/2:]

#Unir B y C - Zip B and C to get a new list of coordinates
zipped = zip(B,C)

#Make a new list from zipped to convert from tuple to list
final_list = [list(elem) for elem in zipped]

#Convert contect of alfacor to tuples
inv_alfacor = {}
for letter, coordinate in alfacor.iteritems():
inv_alfacor[tuple(coordinate)] = letter

#Substitude coordinates of final_list from elements of inv_alfacor
encripta_f = []
for element in final_list:
    element = tuple(element)
    if element in inv_alfacor:
        encripta_f.append(inv_alfacor[element])

print "Tu palabra ",encripta_f    

2 个答案:

答案 0 :(得分:0)

  1. 使用 with 声明
  2. 您可以在python docs或本文Understanding Python's "with" statement

    中阅读更多内容

    建议修改:

    #Leer Txt - Read txt
    with open("Z:\\R\\Desktop\\BIFIDO\\easy.txt", "r") as document:
        contenido = document.read()
        print (contenido)
    
    1. 使用列表推导
    2. Python docs或教程Python Tutorial: List Comprehensions

      中的更多信息

      建议修改:

      #Genera alfabeto-Generate Alphabet
      alfa = [chr(i) for i in xrange(97, 123) if chr(i) != "i"]
      

      (请注意,此更改还包括列表理解中的条件 - example at SO question

      还有:

      #Encripta fase1 - Get's coordinates of txt    
      encripta = [alfacor[e] for e in contenido]
      
      1. 使用生成器
      2. 你可以开始的第一件事就是关注。当您编写列表推导并且您知道一次只迭代列表中的一个项目时,将括号从[]更改为()。这真的很简单,但这是你能做的第一件事。另一个相关提示是,当您range(x)使用for i in range(x)时,请使用xrange(x)xrangerange的生成器版本。

        Python Wiki

        中的更多信息

        建议更改:

        #Make a new list from zipped to convert from tuple to list
        final_list = (list(elem) for elem in zipped)
        
        1. 打印
        2. 在这种情况下,使用您使用的打印很好,但看看字符串格式。

          Python docsfew examples here中的更多内容。

          可能的改变:

          print "Tu palabra {}".format(encripta_f)
          
          1. 不需要初始化所有变量。
          2. 在为变量分配全新值时,无需初始化alfacor字典。但是,稍后使用它时需要初始化变量。

            因此

            之间存在差异
            # no need for initialization
            alfacor = {}
            # because you assign a new value here to the variable `alfacor`
            alfacor = dict(zip(alfa,coordinates))
            

            和此:

            # you need to initialize this
            alfacor = {}
            # because you are working with the empty dictionary here
            alfacor["my_key"] = "my_value"
            

答案 1 :(得分:0)

除了使用理解并避免不必要的元组之外 - >列表 - >元组转换,减少中间变量的数量,然后它可能稍微容易阅读。我还会考虑将它作为一个函数传递给一个字符串并返回一个加密的字符串:

from itertools import chain, product

def bifid(data):
    # Leave coordinates as tuples and appropriate use of itertools.product
    coordinates = product(range(1, 6), repeat=2)

    # Using comprehensions and generators to construct the list/dicts vs loops
    # Leave alfa as a generator as it is only used once
    alfa = (chr(i) for i in range(97, 123) if chr(i) != 'i')
    alfacor = dict(zip(alfa, coordinates))
    inv_alfacor = {coordinate: letter for letter, coordinate in alfacor.iteritems()}
    encripta = (alfacor[e] for e in data)

    merged = list(chain(*encripta))
    final_list = zip(merged[:len(merged)//2], merged[len(merged)//2:])

    return "".join(inv_alfacor[e] for e in final_list if e in inv_alfacor)

# Use with it closes automatically and handles exceptions correctly
with open("Z:\\R\\Desktop\\BIFIDO\\easy.txt") as document:
    data = document.read()]

print "Tu palabra: {}".format(bifid(data))

输出:

"helloworld" -> Tu palabra: kmcyobnalt