原文地址:http://stackoverflow.com/questions/16784041/how-to-think-like-a-computer-scientist-exercise
问题: 我的目的是写一个判断三个值,能否组成三角形的函数,代码如下:
def is_triangle(a,b,c):
num_list = [a,b,c]
biggest = max(num_list)
other_two = num_list.remove(biggest)
sum_of_two = sum(other_two)
if sum_of_two > biggest:
print 'Congrats, %d, %d, and %d form a triangle!' % (a,b,c)
elif sum_of_two == biggest:
print 'That forms a degenerate triangle!'
else:
print 'That does\'t make any sort triangle... >:['
def sides():
side1 = raw_input('Please input side numero Juan: ')
side2 = raw_input('Now side two: ')
side3 = raw_input('...aaaannnd three: ')
import time
time.sleep(1)
print 'Thanks >:]'
side1 = int(side1)
side2 = int(side2)
side3 = int(side3)
is_triangle(side1,side2,side3)
sides()
但运行时会出现如下错误:
Traceback (most recent call last):
File "A:/Python/is_triangle.py", line 27, in <module>
sides()
File "A:/Python/is_triangle.py", line 25, in sides
is_triangle(side1,side2,side3)
File "A:/Python/is_triangle.py", line 5, in is_triangle
sum_of_two = sum(other_two)
TypeError: 'NoneType' object is not iterable
解答1:
这个问题的实质在于 remove这个函数没有返回一个新的list,改成:
num_list.remove(biggest)
sum_of_two = sum(num_list)
即可。
解答2:
这是一个很常见,很简单的错误。在Python之中,当一个函数改变了一个数据结构,它不会返回 被改变的结构,通常它会返回None。
Python这样做的原因是为了遵守“Command/Query Separation”原则,也就是命令查询分离原则
可参考:
http://en.wikipedia.org/wiki/Command%E2%80%93query_separation
http://www.cnblogs.com/youxin/p/3149695.html
解答3:
因为num_list.remove(biggest)返回了None,考虑下面这样:
other1, other2, biggest = sorted(num_list)
sum_of_two = other1 + other2
End.
个人总结:也就是说,remove函数,作为一个Command,它不能再提供查询的功能,所以返回值应该是None;而Sorted,它应该属于Query,它并不改变这个List,它返回一个新的被排序的List。 但怎么判断一个函数式 Command还是Query? 得再研究,体会下。
上述各种类型的实验:
a=[2,1,3,4,6,5]
b=sorted(a)
print(a)
print(b)
c='AFDSDFSDF'
d=str.lower(c)
print(c)
print(d)
e=[3,3,2,3,4]
f=e.remove(2)
print(e)
print(f)
结果为:
[2, 1, 3, 4, 6, 5]
[1, 2, 3, 4, 5, 6]
AFDSDFSDF
afdsdfsdf
[3, 3, 3, 4]
None