fork download
  1.  
  2. def groupCitiesByRotatedName(A):
  3. """Groups cities by anagram pairs"""
  4. result = [[city] for city in A]
  5. anagramMap = {}
  6. for index, city in enumerate(A):
  7. if city.lower() in anagramMap:
  8. origMapIndex = anagramMap[city.lower()]
  9. result[origMapIndex].append(city)
  10. continue
  11.  
  12. rotatedCities = rotateString(city.lower())
  13. # add rotated items to map
  14. anagramMap = {**anagramMap, **{i: index for i in rotatedCities}}
  15. return result
  16.  
  17.  
  18. def rotateString(string):
  19. """Rotates all possible combinations of a string and returns a list"""
  20. N = len(string)
  21. string += string
  22. rotatedStrings = []
  23. for i in range(1, N):
  24. rotatedStrings += [string[i:N + i]]
  25. return rotatedStrings
  26.  
  27.  
  28. def main():
  29. # A = [i for i in input().split()]
  30. A = ['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris']
  31. groupedA = groupCitiesByRotatedName(A)
  32. print(groupedA)
  33.  
  34.  
  35. if __name__ == "__main__":
  36. main()# your code goes here
Success #stdin #stdout 0.02s 9308KB
stdin
Standard input is empty
stdout
[['Tokyo', 'Kyoto'], ['London', 'Donlon'], ['Rome'], ['Donlon'], ['Kyoto'], ['Paris']]