walk.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. class Walk:
  2. def __init__(self,str=None):
  3. if str!=None:
  4. self.__decompress__(str)
  5. def __decompress__(self,str):
  6. self.xmin=0
  7. self.xmax=0
  8. self.ymin=0
  9. self.ymax=0
  10. self.length=0
  11. x=0
  12. y=0
  13. self.steps=[]
  14. valid_steps=['l','r','u','b']
  15. i=0
  16. while i<len(str):
  17. s=str[i]
  18. if not s in valid_steps:
  19. raise AttributeError("Step '"+c+"' unkown")
  20. i+=1
  21. j=i
  22. if i<len(str):
  23. j=i
  24. v=0
  25. while i<len(str) and '0'<=str[i] and str[i]<='9':
  26. v=v*10+ord(str[i])-ord('0')
  27. i+=1
  28. if j==i:
  29. #No digits
  30. v=1
  31. self.length+=v
  32. for k in range(v):
  33. self.steps.append(s)
  34. if s=='l':
  35. x+=v
  36. self.xmax=max(self.xmax,x)
  37. elif s=='r':
  38. x-=v
  39. self.xmin=min(self.xmin,x)
  40. elif s=='u':
  41. y+=v
  42. self.ymax=max(self.ymax,y)
  43. else: # s=='b'
  44. y-=v
  45. self.ymin=min(self.ymin,y)
  46. def show(self):
  47. G=Graphics()
  48. for x in range(self.xmin-1,self.xmax+2):
  49. G+=line2d([(x,self.ymin-1),(x,self.ymax+1)],thickness=1,rgbcolor=(0.5,0.5,0.5))
  50. for y in range(self.ymin-1,self.ymax+2):
  51. G+=line2d([(self.xmin-1,y),(self.xmax+1,y)],thickness=1,rgbcolor=(0.5,0.5,0.5))
  52. P=[(0,0)]
  53. x=0
  54. y=0
  55. for s in self.steps:
  56. if s=='l':
  57. x+=1
  58. elif s=='r':
  59. x-=1
  60. elif s=='u':
  61. y+=1
  62. else:
  63. y-=1
  64. P.append((x,y))
  65. G+=line2d(P,thickness=3)
  66. G.show(axes=False,aspect_ratio=1)
  67. def is_self_avoiding_polygon(self):
  68. x=0
  69. y=0
  70. v=set([(0,0)])
  71. l=0
  72. for s in self.steps:
  73. l+=1
  74. if s=='r':
  75. x+=1
  76. elif s=='l':
  77. x-=1
  78. elif s=='u':
  79. y+=1
  80. else:
  81. y-=1
  82. if l<self.length and (x,y) in v:
  83. return False
  84. if l==self.length:
  85. return (x,y)==(0,0)
  86. def polygon(self):
  87. if not self.is_self_avoiding_polygon():
  88. raise RuntimeError("This walk is not a self avoiding polygon")
  89. print("Ok lets go")