Skip to content

Commit

Permalink
Use attrgetter("fscore"), generator instead of lambda, and map respec…
Browse files Browse the repository at this point in the history
…tively.. (#33)

operator.attrgetter will outperform lambda calls. see: https://docs.python.org/3/howto/sorting.html#operator-module-functions-and-partial-function-evaluation

Generator expressions (since Python 3.x) will be more performant, feature rich, and Pythonic, than map. See: https://peps.python.org/pep-0289/
  • Loading branch information
pygeek authored Jun 2, 2024
1 parent c3c05ef commit 03a3270
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions astar/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from abc import ABC, abstractmethod
from typing import Callable, Dict, Iterable, Union, TypeVar, Generic
from math import inf as infinity
from operator import attrgetter
import sortedcontainers # type: ignore

# introduce generic type
Expand Down Expand Up @@ -47,7 +48,7 @@ def __missing__(self, k) -> SearchNode[T]:

class OpenSet(Generic[SNType]):
def __init__(self) -> None:
self.sortedlist = sortedcontainers.SortedList(key=lambda x: x.fscore)
self.sortedlist = sortedcontainers.SortedList(key=attrgetter("fscore"))

def push(self, item: SNType) -> None:
item.in_openset = True
Expand Down Expand Up @@ -98,6 +99,9 @@ def neighbors(self, node: T) -> Iterable[T]:
"""
raise NotImplementedError

def _neighbors(self, current: SearchNode[T], search_nodes: SearchNodeDict[T]) -> Iterable[SearchNode]:
return (search_nodes[n] for n in self.neighbors(current.data))

def is_goal_reached(self, current: T, goal: T) -> bool:
"""
Returns true when we can consider that 'current' is the goal.
Expand Down Expand Up @@ -139,7 +143,7 @@ def astar(

current.closed = True

for neighbor in map(lambda n: searchNodes[n], self.neighbors(current.data)):
for neighbor in self._neighbors(current, searchNodes):
if neighbor.closed:
continue

Expand Down

0 comments on commit 03a3270

Please sign in to comment.