Last active
February 9, 2020 13:56
-
-
Save miraculixx/704ec20b1536b4b3acef1e15e9c85d9c to your computer and use it in GitHub Desktop.
map cities by rotated letters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import combinations | |
# quick and dirty implementation, not optimized | |
cities = ['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris'] | |
normalized = [(c, ''.join(sorted(c.lower()))) for c in cities] | |
cartesian = list(combinations(normalized, 2)) | |
matches = [[l[0], r[0]] for l, r in cartesian if l[1] == r[1]] | |
matches.extend([c for c in cities if c not in [m[0] for m in matches] + [m[1] for m in matches]]) | |
matches | |
# output [['Tokyo', 'Kyoto'], ['London', 'Donlon'], 'Rome', 'Paris'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# improved version by only rotating, not sorting | |
# -- rotate i times to the left | |
rot = lambda s, i: s[i:] + s[0:(i)] | |
# -- keep unrotated with i == 0, rotate every possible way | |
rotated = [(i, c, rot(c.lower(), i)) for c in cities for i in range(len(c))] | |
# -- find matches where left is equal to right and right is the original name | |
matches = [(l[1], r[1]) for l, r in combinations(rotated, 2) if l[2] == r[2] and r[0] == 0] | |
matches.extend([c for c in cities if c not in [m[0] for m in matches] + [m[1] for m in matches]]) | |
matches | |
# output [('Tokyo', 'Kyoto'), ('London', 'Donlon'), 'Rome', 'Paris'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cities = ['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris'] | |
# actually, can be done in 3 statements, without combinatorics. ok it starts to get somewhat involved | |
rot = lambda s, i: s[i:] + s[0:(i)] | |
matches = [(c, rot(c.lower(), i).capitalize()) | |
for j, c in enumerate(cities) | |
for i in range(len(c)) | |
if rot(c.lower(), i) in [cx.lower() for cx in cities[j:]] and i > 0] | |
matches.extend([c for c in cities if c not in [m[0] for m in matches] + [m[1] for m in matches]]) | |
matches | |
# output [('Tokyo', 'Kyoto'), ('London', 'Donlon'), 'Rome', 'Paris'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python solution to https://hackernoon.com/how-to-lose-an-it-job-in-10-minutes-3d63213c8370