Python的话,直接执行"import this"就有你要的答案。
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
大致翻译如下:
优美胜于丑陋
明了胜于含蓄
简洁胜于复杂
复杂胜于难解
扁平胜于嵌套
稀疏胜于密集
可读性真的重要
没有特例能特殊到违背规则
尽管实用性超过存粹性
错误永远不应该忽视
除非显式地忽略
在歧义面前,拒绝猜测的诱惑
应该有一种——最好只有一种——明显的解决方法
尽管这个方法一开始并不明显,毕竟你不是大神Guido
现在做胜于永远不做
但是欲速则不达
难以解释的方案,是馊主意
容易解释的方案,是好主意
命名空间很棒,多多益善
不要教条地看简练,还是篇幅。题主您举的这三行,并没有实质性的可读性的差距。两种写法都没有很大的差别。我觉着,写在一行里,也没有很难懂。
print("Total wage:",float(input("Hourly rate:"))*float(input("Total hours:")))
因为代码逻辑本身太简单,写成一行也不长,不是很明显的。
我举个例子,求矩阵的行列式值。一种写法是这样:
def determinant(m):
result = 0
if len(m) == 1:
result = m[0][0]
else:
for n in range(len(m)):
if (n + 1) % 2 == 0:
result -= m[0][n] * determinant([o[:n] + o[n+1:] for o in m[1:]])
else:
result += m[0][n] * determinant([o[:n] + o[n+1:] for o in m[1:]])
return result
第二种写法是这样:
def determinant(matrix):
return reduce(lambda r, i:r+(-1)**i*matrix[0][i]*determinant([m[:i]+m[i+1:] for m in matrix[1:]]),range(len(matrix[0])),0) if len(matrix) != 1 else matrix[0][0]
第三种写法是这样的:
def determinant(matrix):
if len(matrix) == 1:
return matrix[0][0]
side = 1
total = 0
for i in range(len(matrix)):
total+= side * matrix[0][i] * determinant(matrix_without_index(matrix,i))
side *= -1
return total
def matrix_without_index(matrix, index):
mat = []
for i in matrix:
temp_list = []
for j in i:
temp_list.append(j)
mat.append(temp_list)
mat.pop(0)
for i in range(len(mat)):
mat[i].pop(index)
return mat
很显然,第一种写法的可读性最好,篇幅不是最少,也不是最多。