如何将不等式作为变量传递给函数,然后对其进行求值?

时间:2015-02-28 00:50:49

标签: python

def bubble_up(heap, inequality):
  print heap, 'bubbling up', heap[-1]
  heap_length = len(heap)
  position = heap_length - 1 #heap_length
  parent = int(heap_length/2) - 1
  print 'parent =', heap[parent]
  while heap[position] inequality heap[parent]:

那不起作用!
我想通过不平等,并对其进行评估,我希望它能清楚地表明我在6个月内所做的事情。 我也希望它快。如果用改变的符号写两个函数会好得多,请大声说出原因。

1 个答案:

答案 0 :(得分:1)

设计bubble_up函数以将inequality作为函数调用:

while inequality(heap[position], heap[parent]):

然后传入函数,评估所需的不等式。

您可以使用Python的lambda关键字在调用bubble_up时定义不等式函数,而无需为其命名:

bubble_up(my_heap, lambda x, y: x < y)

或者您可以在operator模块中使用已为您定义的功能:

import operator

bubble_up(my_heap, operator.lt)

如果您经常使用特定的不等式,请在函数定义中将其用作默认值:

def bubble_up(heap, inequality=operator.lt):
    # and so on
相关问题