gpt4 book ai didi

python - 如何强制自己更优雅地编码?

转载 作者:行者123 更新时间:2023-11-28 19:02:57 25 4
gpt4 key购买 nike

<分区>

我注意到与其他人相比,我的编码风格往往非常暴力。例如,一个练习题要求我们通过一个类来创建一个密码。密码将接受一个字符串并使用两个系列的字母表对字符串进行编码和解码。例如:

map1 = "abcdefghijklmnopqrstuvwxyz"
map2 = "etaoinshrdlucmfwypvbgkjqxz"

cipher = Cipher(map1, map2);
cipher.encode("abc") => "eta"

我通过编写以下内容成功完成了这个练习题:

class Cipher(object):
def __init__(self, map1, map2):
self.map1=map1
self.map2=map2

def encode(self, string):
string=list(string)
string_pos=[self.map1.index(i) if i.isalpha() else i for i in string]
string_enc=[self.map2[i] if isinstance(i, int) else i for i in string_pos]
return ''.join(string_enc)

def decode(self, string):
string=list(string)
string_pos=[self.map2.index(i) if i.isalpha() else i for i in string]
string_dec=[self.map1[i] if isinstance(i, int) else i for i in string_pos]
return ''.join(string_dec)

然而,其他人以我认为更直接的方式完成了同样的练习题:

from string import maketrans

class Cipher(object):
def __init__(self, map1, map2):
self.encode_table = maketrans(map1, map2)
self.decode_table = maketrans(map2, map1)
def encode(self, string):
return string.translate(self.encode_table)
def decode(self, string):
return string.translate(self.decode_table)

我怎样才能强制/教自己开始编写更优雅、更直接的代码并逐渐摆脱类似蛮力的代码?为此,您会推荐哪些阅读资源?是否有任何您知道的技巧可以提供帮助,例如“如果您看到自己在使用 x,请记住 y 做同样的事情更优雅?”

如有任何帮助,我们将不胜感激。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com