1
0

builtins.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. from pkpy import next as __pkpy_next
  2. def all(iterable):
  3. for i in iterable:
  4. if not i:
  5. return False
  6. return True
  7. def any(iterable):
  8. for i in iterable:
  9. if i:
  10. return True
  11. return False
  12. def enumerate(iterable, start=0):
  13. n = start
  14. for elem in iterable:
  15. yield n, elem
  16. n += 1
  17. def sum(iterable):
  18. res = 0
  19. for i in iterable:
  20. res += i
  21. return res
  22. def map(f, iterable):
  23. for i in iterable:
  24. yield f(i)
  25. def filter(f, iterable):
  26. for i in iterable:
  27. if f(i):
  28. yield i
  29. def zip(a, b):
  30. a = iter(a)
  31. b = iter(b)
  32. while True:
  33. ai = __pkpy_next(a)
  34. bi = __pkpy_next(b)
  35. if ai is StopIteration or bi is StopIteration:
  36. break
  37. yield ai, bi
  38. def reversed(iterable):
  39. a = list(iterable)
  40. a.reverse()
  41. return a
  42. def sorted(iterable, key=None, reverse=False):
  43. a = list(iterable)
  44. a.sort(key=key, reverse=reverse)
  45. return a
  46. ##### str #####
  47. def __format_string(self: str, *args, **kwargs) -> str:
  48. def tokenizeString(s: str):
  49. tokens = []
  50. L, R = 0,0
  51. mode = None
  52. curArg = 0
  53. # lookingForKword = False
  54. while(R<len(s)):
  55. curChar = s[R]
  56. nextChar = s[R+1] if R+1<len(s) else ''
  57. # Invalid case 1: stray '}' encountered, example: "ABCD EFGH {name} IJKL}", "Hello {vv}}", "HELLO {0} WORLD}"
  58. if curChar == '}' and nextChar != '}':
  59. raise ValueError("Single '}' encountered in format string")
  60. # Valid Case 1: Escaping case, we escape "{{ or "}}" to be "{" or "}", example: "{{}}", "{{My Name is {0}}}"
  61. if (curChar == '{' and nextChar == '{') or (curChar == '}' and nextChar == '}'):
  62. if (L<R): # Valid Case 1.1: make sure we are not adding empty string
  63. tokens.append(s[L:R]) # add the string before the escape
  64. tokens.append(curChar) # Valid Case 1.2: add the escape char
  65. L = R+2 # move the left pointer to the next char
  66. R = R+2 # move the right pointer to the next char
  67. continue
  68. # Valid Case 2: Regular command line arg case: example: "ABCD EFGH {} IJKL", "{}", "HELLO {} WORLD"
  69. elif curChar == '{' and nextChar == '}':
  70. if mode is not None and mode != 'auto':
  71. # Invalid case 2: mixing automatic and manual field specifications -- example: "ABCD EFGH {name} IJKL {}", "Hello {vv} {}", "HELLO {0} WORLD {}"
  72. raise ValueError("Cannot switch from manual field numbering to automatic field specification")
  73. mode = 'auto'
  74. if(L<R): # Valid Case 2.1: make sure we are not adding empty string
  75. tokens.append(s[L:R]) # add the string before the special marker for the arg
  76. tokens.append("{"+str(curArg)+"}") # Valid Case 2.2: add the special marker for the arg
  77. curArg+=1 # increment the arg position, this will be used for referencing the arg later
  78. L = R+2 # move the left pointer to the next char
  79. R = R+2 # move the right pointer to the next char
  80. continue
  81. # Valid Case 3: Key-word arg case: example: "ABCD EFGH {name} IJKL", "Hello {vv}", "HELLO {name} WORLD"
  82. elif (curChar == '{'):
  83. if mode is not None and mode != 'manual':
  84. # # Invalid case 2: mixing automatic and manual field specifications -- example: "ABCD EFGH {} IJKL {name}", "Hello {} {1}", "HELLO {} WORLD {name}"
  85. raise ValueError("Cannot switch from automatic field specification to manual field numbering")
  86. mode = 'manual'
  87. if(L<R): # Valid case 3.1: make sure we are not adding empty string
  88. tokens.append(s[L:R]) # add the string before the special marker for the arg
  89. # We look for the end of the keyword
  90. kwL = R # Keyword left pointer
  91. kwR = R+1 # Keyword right pointer
  92. while(kwR<len(s) and s[kwR]!='}'):
  93. if s[kwR] == '{': # Invalid case 3: stray '{' encountered, example: "ABCD EFGH {n{ame} IJKL {", "Hello {vv{}}", "HELLO {0} WOR{LD}"
  94. raise ValueError("Unexpected '{' in field name")
  95. kwR += 1
  96. # Valid case 3.2: We have successfully found the end of the keyword
  97. if kwR<len(s) and s[kwR] == '}':
  98. tokens.append(s[kwL:kwR+1]) # add the special marker for the arg
  99. L = kwR+1
  100. R = kwR+1
  101. # Invalid case 4: We didn't find the end of the keyword, throw error
  102. else:
  103. raise ValueError("Expected '}' before end of string")
  104. continue
  105. R = R+1
  106. # Valid case 4: We have reached the end of the string, add the remaining string to the tokens
  107. if L<R:
  108. tokens.append(s[L:R])
  109. # print(tokens)
  110. return tokens
  111. tokens = tokenizeString(self)
  112. argMap = {}
  113. for i, a in enumerate(args):
  114. argMap[str(i)] = a
  115. final_tokens = []
  116. for t in tokens:
  117. if t[0] == '{' and t[-1] == '}':
  118. key = t[1:-1]
  119. argMapVal = argMap.get(key, None)
  120. kwargsVal = kwargs.get(key, None)
  121. if argMapVal is None and kwargsVal is None:
  122. raise ValueError("No arg found for token: "+t)
  123. elif argMapVal is not None:
  124. final_tokens.append(str(argMapVal))
  125. else:
  126. final_tokens.append(str(kwargsVal))
  127. else:
  128. final_tokens.append(t)
  129. return ''.join(final_tokens)
  130. str.format = __format_string
  131. del __format_string
  132. def help(obj):
  133. if hasattr(obj, '__func__'):
  134. obj = obj.__func__
  135. # print(obj.__signature__)
  136. if obj.__doc__:
  137. print(obj.__doc__)
  138. def complex(real, imag=0):
  139. import cmath
  140. return cmath.complex(real, imag)
  141. class set:
  142. def __init__(self, iterable=None):
  143. iterable = iterable or []
  144. self._a = {}
  145. self.update(iterable)
  146. def add(self, elem):
  147. self._a[elem] = None
  148. def discard(self, elem):
  149. self._a.pop(elem, None)
  150. def remove(self, elem):
  151. del self._a[elem]
  152. def clear(self):
  153. self._a.clear()
  154. def update(self, other):
  155. for elem in other:
  156. self.add(elem)
  157. def __len__(self):
  158. return len(self._a)
  159. def copy(self):
  160. return set(self._a.keys())
  161. def __and__(self, other):
  162. return {elem for elem in self if elem in other}
  163. def __sub__(self, other):
  164. return {elem for elem in self if elem not in other}
  165. def __or__(self, other):
  166. ret = self.copy()
  167. ret.update(other)
  168. return ret
  169. def __xor__(self, other):
  170. _0 = self - other
  171. _1 = other - self
  172. return _0 | _1
  173. def union(self, other):
  174. return self | other
  175. def intersection(self, other):
  176. return self & other
  177. def difference(self, other):
  178. return self - other
  179. def symmetric_difference(self, other):
  180. return self ^ other
  181. def __eq__(self, other):
  182. if not isinstance(other, set):
  183. return NotImplemented
  184. return len(self ^ other) == 0
  185. def __ne__(self, other):
  186. if not isinstance(other, set):
  187. return NotImplemented
  188. return len(self ^ other) != 0
  189. def isdisjoint(self, other):
  190. return len(self & other) == 0
  191. def issubset(self, other):
  192. return len(self - other) == 0
  193. def issuperset(self, other):
  194. return len(other - self) == 0
  195. def __contains__(self, elem):
  196. return elem in self._a
  197. def __repr__(self):
  198. if len(self) == 0:
  199. return 'set()'
  200. return '{'+ ', '.join([repr(i) for i in self._a.keys()]) + '}'
  201. def __iter__(self):
  202. return iter(self._a.keys())