2016-11-04 10 views
0

優先度を評価する関数を使用して、優先度キューを実装するクラスが与えられました。1つの変数を持つ2つの引数を関数に渡すにはどうすればよいですか?

class PriorityQueueWithFunction(PriorityQueue): 
    """ 
    Implements a priority queue with the same push/pop signature of the 
    Queue and the Stack classes. This is designed for drop-in replacement for 
    those two classes. The caller has to provide a priority function, which 
    extracts each item's priority. 
    """ 
    def __init__(self, priorityFunction): 
     # type: (object) -> object 
     "priorityFunction (item) -> priority" 
     self.priorityFunction = priorityFunction  # store the priority function 
     PriorityQueue.__init__(self)  # super-class initializer 

    def push(self, item): 
     "Adds an item to the queue with priority from the priority function" 
     PriorityQueue.push(self, item, self.priorityFunction(item)) 

上記のクラスを初期化する優先度関数も与えられました。

def manhattanHeuristic(position, problem, info={}): 
    "The Manhattan distance heuristic for a PositionSearchProblem" 
    xy1 = position 
    xy2 = problem.goal 
    return abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1]) 

上記のコードは私たちに与えられており、変更することはできません。私はそのPriorityQueueWithFunctionクラスを作成し、それに要素をプッシュする必要があります。 プッシュ私のクラスの機能は引数、項目を取ります。しかし、私のPriorityFunctionは2になります。 私のクラスに正しいelemntをプッシュして、私の優先順位関数を適切に動作させるためには、どんな種類の引数を使うべきですか?

私が試したものだと、私はエラーをコンパイル取得していますmanhattanHeuristic ...は、2つの引数を取り、

#Creating a queingFn 
queuingFn = PriorityQueueWithFunction(heuristic) 
Frontier = queuingFn 
#Creating the item that needs to be pushed 
StartState = problem.getStartState() 
StartNode = (StartState,'',0,(-1,-1)) 
#Here is my problem 
item = StartState , problem 
Frontier.push(item) 

与えられた1は、私は私のアイテムのフォームを変更する必要がありますか?何か案は ?

+0

PriorityQueueWithFunctionに渡し** kwargs' 。それらは、1つ(または2つ)の変数を使用して関数内の任意の量のデータを渡すことを可能にします。それらを関数内でアンパックすることができます。 –

+0

あなたの場合、おそらく、 'item'の前に' * '星を追加するだけの簡単なはずです。 –

答えて

0

あなたはmanhattanHeuristicへの呼び出しをラップし、新たな方法で行う必要があります。 `* args``を見てみると

# for item as dict: item = {'position': POS, 'problem': PROBLEM} 
def oneArgHeuristic(item): 
    position = item.position 
    problem = item.problem 
    return manhattanHeuristic(position, problem) 

# for item as tuple: item = (POS, PROBLEM) 
def oneArgHeuristic(item): 
    position, problem = item 
    return manhattanHeuristic(position, problem) 

をし、代わりに、元の1

関連する問題