You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4 年之前
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import doctest
  2. import itertools
  3. import sys
  4. def swap(text, a1, a2):
  5. if str(a1).isdigit():
  6. a1 = text[int(a1)]
  7. if str(a2).isdigit():
  8. a2 = text[int(a2)]
  9. return text.translate(str.maketrans(a1 + a2, a2 + a1))
  10. def reverse(text, a1, a2):
  11. a1, a2 = int(a1), int(a2) + 1
  12. return text[:a1] + text[a1:a2][::-1] + text[a2:]
  13. def rotate_left(text, n):
  14. return text[n:] + text[:n]
  15. def rotate_right(text, n):
  16. return rotate_left(text, -n)
  17. def rotate_based(text, c):
  18. n = text.index(c)
  19. if n >= 4:
  20. n += 1
  21. n += 1
  22. n %= len(text)
  23. return text[-n:] + text[:-n]
  24. def move(text, a1, a2):
  25. c = text[a1]
  26. text = text[:a1] + text[a1 + 1:]
  27. return text[:a2] + c + text[a2:]
  28. def scramble(text):
  29. '''
  30. >>> swap('abcde', 4, 0)
  31. 'ebcda'
  32. >>> swap(_, 'd', 'b')
  33. 'edcba'
  34. >>> reverse(_, 0, 4)
  35. 'abcde'
  36. >>> rotate_left(_, 1)
  37. 'bcdea'
  38. >>> move(_, 1, 4)
  39. 'bdeac'
  40. >>> move(_, 3, 0)
  41. 'abdec'
  42. >>> rotate_based(_, 'b')
  43. 'ecabd'
  44. >>> rotate_based(_, 'd')
  45. 'decab'
  46. '''
  47. for line in instructions:
  48. fn, *args = line.replace('rotate ', 'rotate_').split(' ')
  49. args = [int(c) if c.isdigit() else c for c in args if len(c) == 1]
  50. text = eval(fn)(text, *args)
  51. return text
  52. instructions = sys.stdin.read().splitlines()
  53. doctest.testmod()
  54. print(scramble('abcdefgh'))
  55. for perm in [''.join(seq) for seq in itertools.permutations('abcdefgh')]:
  56. if scramble(perm) == 'fbgdceah':
  57. print(perm)