我是python的初学者,我通过编写算法和数据结构程序来学习python中的语法和其他函数。
如何改进这些代码?
def get_input(): #to get input from user
input_str = input("Enter elements to be sorted: ")
try:
lst = list(map(int, input_str.split())) #make a list of integers from input string
except:
raise TypeError("Please enter a list of integers only, seperated by a space!!")
return lst
def max_heapify(thelist, lst_size, idx):
largest = idx
left_child = (2 * idx) + 1
right_child = (2 * idx) + 2
if left_child < lst_size and thelist[left_child] > thelist[largest]:
largest = left_child
if right_child < lst_size and thelist[right_child] > thelist[largest]:
largest = right_child
if largest != idx:
thelist[idx], thelist[largest] = thelist[largest], thelist[idx]
max_heapify(thelist, lst_size, largest)
def build_max_heap(thelist, lst_size):
for curr_idx in range(lst_size // 2 - 1, -1, -1):
max_heapify(thelist, lst_size, curr_idx)
def heap_sort(thelist):
if len(thelist) == 0:
print("Empty list!!")
elif len(thelist) == 1:
print("Only one element!!")
else:
build_max_heap(thelist, len(thelist))
for curr_idx in range(len(thelist) -1, 0, -1):
thelist[curr_idx], thelist[0] = thelist[0], thelist[curr_idx] #swapping
max_heapify(thelist, curr_idx, 0)
if __name__ == '__main__':
input_list = get_input()
heap_sort(input_list)
print(*input_list, sep = ", ")发布于 2019-07-06 13:16:38
本评论如下:
to get input from user最好放在docstring中:
def get_input():
"""
get input from user
"""最好用谷歌搜索,因为它有大量的信息,但举个例子:idx参数将是idx: int。
(2 * idx) + 1不需要父母,因为乘法比加法有更强的关联。
except:至少,您应该编写except Exception而不是except。后者可以防止用户中断(Ctrl+C)工作。如果可能,将异常替换为更具体的内容。
map有点难读。相反,不如
lst = [int(e) for e in input_str.split()]lst是没有帮助的--而不是根据它们的类型命名,您应该根据它们对程序的实际意义来命名它们--在这种情况下,可能是“元素”。
https://codereview.stackexchange.com/questions/223609
复制相似问题