2015-04-07 59 views
-1

我是絕對新的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  
+1

這個問題看起來更切合主題爲[代碼審查(HTTP ://codereview.stackexchange.com/help/on-topic)。詢問關於代碼風格的觀點在這裏是無關緊要的。 – Radiodef

+0

感謝您的提示,不知道它,將在未來的職位上想到。 – etsous

回答

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 
+0

我非常感謝代碼縮減,非常感謝。 – etsous

0
  1. 使用with聲明

你可以閱讀更多的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) 
  • 使用列表內涵
  • 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] 
    
  • 使用發電機
  • 你可以跟隨啓動的第一件事。當你編寫一個列表理解,並且你知道你將只迭代列表中的一個項目時,將括號從[]更改爲()。這真的很簡單,但它是你可以做的第一件事。另一個相關的提示,當您使用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) 
    
  • 印刷
  • 在這種情況下,使用用於打印是很好,但看看字符串格式。

    更多Python docsfew examples here

    可能的變化:

    print "Tu palabra {}".format(encripta_f) 
    
  • 不需要初始化所有的變量。
  • 當您爲變量賦予一個全新的值時,不需要初始化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" 
    
    +0

    你應該擺脫額外的開放聲明 – AChampion

    +0

    @achampion謝謝,修正。 – Marek

    +0

    @Marek哇,非常感謝您的詳細解釋,這將在不久的將來真正幫助。 – etsous