I am trying to implement the A* algorithm in Python as a learning exercise. I have a list of nodes, called open
, that contains strings that represent the names of graph nodes. Example: open["node_a", "node_b", "node_c"]
. I also have two defaultdict
dictionaries, f_estim
and g
, that contain values like {"name_of_node" : integer_representing_a_certain_cost_associated_to_the_node}
. I am required to sort the open
list ascending by the value associated in f_estim
, and if that value is equal for two nodes, descending according to the value in g
. I am sorting ascending like so: open.sort(key=lambda node: f_estim[node])
. How can i also sort descending when reaching two equal values? I could not find the answer in the documentation of the sort
function. Thank you!
Asked
Active
Viewed 42 times
-1

M_S
- 25
- 1
- 3
-
have you tried sorted funtion [example](https://stackoverflow.com/questions/19199984/sort-a-list-in-python) – Shubham Shaswat Mar 21 '20 at 11:00
-
Please add full examples (input and expected output) – Dani Mesejo Mar 21 '20 at 11:02
-
3Your lambda can return a tuple with primary criterion first and negative of secondary criterion second. – Michael Butscher Mar 21 '20 at 11:03
-
Have you tried doing something like this ? open.sort(key=lambda node: (f_estim[node], -g[node)) – Osama A.Rehman Mar 21 '20 at 11:03
-
Examples: open ["a", "b", "c", "d"] f_estim {"a" : 5, "b" : 5, "c" : 4, " d" : 4} g: {"a" : 1, "b" : 2, "c" : 3, " d" : 4} after open.sort(???), i want to obtain open["d", "c", "b", "a"] – M_S Mar 21 '20 at 11:09
-
The tuple suggestion is the solution to my problem. Thank you very much everyone for your help! – M_S Mar 21 '20 at 11:13
1 Answers
0
You could do something like this:
open.sort(key=lambda node: (f_estim[node], -g[node]))

Osama A.Rehman
- 912
- 1
- 6
- 12
-
Note that this will only work for ordering criteria that are numeric, and not for other types of comparable criteria (e.g. strings) – newacct Sep 13 '20 at 03:51