1
0

builtins.py 9.0 KB

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