builtins.py 8.6 KB

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