Reikriam

ListOffsetArraygen

Jul 12th, 2020
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. from reducers import Content
  2. from reducers import random_length
  3. import random
  4.  
  5. class ListOffsetArray(Content):
  6. def __init__(self, offsets, content):
  7. assert isinstance(offsets, list)
  8. assert isinstance(content, Content)
  9. assert len(offsets) != 0
  10. for i in range(len(offsets) - 1):
  11. start = offsets[i]
  12. stop = offsets[i + 1]
  13. assert isinstance(start, int)
  14. assert isinstance(stop, int)
  15. if start != stop:
  16. assert start < stop # i.e. start <= stop
  17. assert start >= 0
  18. assert stop <= len(content)
  19. self.offsets = offsets
  20. self.content = content
  21.  
  22. @staticmethod
  23. def random(minlen, choices):
  24. counts = [random_length(minlen) for i in range(random_length(minlen))]
  25. offsets = [random_length()]
  26. for x in counts:
  27. offsets.append(offsets[-1] + x)
  28. return ListOffsetArray(offsets, random.choice(choices).random(offsets[-1], choices))
  29.  
  30. def __len__(self):
  31. return len(self.offsets) - 1
  32.  
  33. def __getitem__(self, where):
  34. if isinstance(where, int):
  35. assert 0 <= where < len(self)
  36. return self.content[self.offsets[where]:self.offsets[where + 1]]
  37. elif isinstance(where, slice) and where.step is None:
  38. offsets = self.offsets[where.start : where.stop + 1]
  39. if len(offsets) == 0:
  40. offsets = [0]
  41. return ListOffsetArray(offsets, self.content)
  42. elif isinstance(where, str):
  43. return ListOffsetArray(self.offsets, self.content[where])
  44. else:
  45. raise AssertionError(where)
  46.  
  47. def __repr__(self):
  48. return "ListOffsetArray(" + repr(self.offsets) + ", " + repr(self.content) + ")"
  49.  
  50. def xml(self, indent="", pre="", post=""):
  51. out = indent + pre + "<ListOffsetArray>\n"
  52. out += indent + " <offsets>" + " ".join(str(x) for x in self.offsets)
  53. out += "</offsets>\n"
  54. out += self.content.xml(indent + " ", "<content>", "</content>\n")
  55. out += indent + "</ListOffsetArray>" + post
  56. return out
  57.  
  58. if __name__ == "__main__":
  59. ListOffsetArray.random(4, [0, 1, 5, 4, 3, 2])
  60.  
  61.  
  62. Traceback (most recent call last):
  63. File "ListOffsetArraygen.py", line 60, in <module>
  64. ListOffsetArray.random(4, [0, 1, 5, 4, 3, 2])
  65. File "ListOffsetArraygen.py", line 29, in random
  66. return ListOffsetArray(offsets, random.choice(choices).random(offsets[-1], choices))
  67. AttributeError: 'int' object has no attribute 'random'
Add Comment
Please, Sign In to add comment