New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Making Entity and Position hashable in Python3 starter kit #170

Merged
merged 2 commits into from Dec 2, 2018

Conversation

Projects
None yet
3 participants
@coreylowman
Copy link
Contributor

coreylowman commented Nov 30, 2018

A nice way to speed things up is to pre-compute things and save them in a dict. For example:

distance_by_position = {p: game_map.calculate_distance(ship.position, p) for p in positions}

You can then use it very easily in the built in functions min, max, sorted, etc.:

sorted_positions = sorted(positions, key=distance_by_position.get)
best_position = min(positions, key=distance_by_position.get)

As of now, both Position and Entities are not hashable, meaning you can't use them as keys in a dict, or even save them in a set.

This PR implements the hash method for both Position and Entity, making the above possible.

@@ -29,6 +29,9 @@ def __repr__(self):
self.id,
self.position)

def __hash__(self):

This comment has been minimized.

@lidavidm

lidavidm Dec 2, 2018

Contributor

You also need to override __eq__ (or make entity instances persistent) if you want this to work in a hash map between turns.

This comment has been minimized.

@snaar

snaar Dec 2, 2018

Contributor

Also note that shipyard has entity id -1, so for equality you also want to check for other fields if entity id is -1.

This comment has been minimized.

@coreylowman

coreylowman Dec 2, 2018

Author Contributor

Alright I've updated so both hash and eq consider the id & owner. Is that sufficient?

@lidavidm lidavidm requested a review from snaar Dec 2, 2018

@snaar

This comment has been minimized.

Copy link
Contributor

snaar commented Dec 2, 2018

Looks fine to me if the comments are addressed.

@snaar snaar merged commit adc3e8f into HaliteChallenge:master Dec 2, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment