builtins.py 8.3 KB

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