builtins.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 max(*args, key=None):
  6. if key is None:
  7. key = lambda x: x
  8. if len(args) == 0:
  9. raise TypeError('max expected 1 arguments, got 0')
  10. if len(args) == 1:
  11. args = args[0]
  12. args = iter(args)
  13. res = next(args)
  14. if res is StopIteration:
  15. raise ValueError('max() arg is an empty sequence')
  16. while True:
  17. i = next(args)
  18. if i is StopIteration:
  19. break
  20. if key(i) > key(res):
  21. res = i
  22. return res
  23. def min(*args, key=None):
  24. if key is None:
  25. key = lambda x: x
  26. if len(args) == 0:
  27. raise TypeError('min expected 1 arguments, got 0')
  28. if len(args) == 1:
  29. args = args[0]
  30. args = iter(args)
  31. res = next(args)
  32. if res is StopIteration:
  33. raise ValueError('min() arg is an empty sequence')
  34. while True:
  35. i = next(args)
  36. if i is StopIteration:
  37. break
  38. if key(i) < key(res):
  39. res = i
  40. return res
  41. def all(iterable):
  42. for i in iterable:
  43. if not i:
  44. return False
  45. return True
  46. def any(iterable):
  47. for i in iterable:
  48. if i:
  49. return True
  50. return False
  51. def enumerate(iterable, start=0):
  52. n = start
  53. for elem in iterable:
  54. yield n, elem
  55. ++n
  56. def sum(iterable):
  57. res = 0
  58. for i in iterable:
  59. res += i
  60. return res
  61. def map(f, iterable):
  62. for i in iterable:
  63. yield f(i)
  64. def filter(f, iterable):
  65. for i in iterable:
  66. if f(i):
  67. yield i
  68. def zip(a, b):
  69. a = iter(a)
  70. b = iter(b)
  71. while True:
  72. ai = next(a)
  73. bi = next(b)
  74. if ai is StopIteration or bi is StopIteration:
  75. break
  76. yield ai, bi
  77. def reversed(iterable):
  78. a = list(iterable)
  79. a.reverse()
  80. return a
  81. def sorted(iterable, reverse=False, key=None):
  82. a = list(iterable)
  83. a.sort(reverse=reverse, key=key)
  84. return a
  85. ##### str #####
  86. def __f(self:str, *args, **kwargs) -> str:
  87. def tokenizeString(s:str):
  88. tokens = []
  89. L, R = 0,0
  90. mode = None
  91. curArg = 0
  92. # lookingForKword = False
  93. while(R<len(s)):
  94. curChar = s[R]
  95. nextChar = s[R+1] if R+1<len(s) else ''
  96. # Invalid case 1: stray '}' encountered, example: "ABCD EFGH {name} IJKL}", "Hello {vv}}", "HELLO {0} WORLD}"
  97. if curChar == '}' and nextChar != '}':
  98. raise ValueError("Single '}' encountered in format string")
  99. # Valid Case 1: Escaping case, we escape "{{ or "}}" to be "{" or "}", example: "{{}}", "{{My Name is {0}}}"
  100. if (curChar == '{' and nextChar == '{') or (curChar == '}' and nextChar == '}'):
  101. if (L<R): # Valid Case 1.1: make sure we are not adding empty string
  102. tokens.append(s[L:R]) # add the string before the escape
  103. tokens.append(curChar) # Valid Case 1.2: add the escape char
  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 2: Regular command line arg case: example: "ABCD EFGH {} IJKL", "{}", "HELLO {} WORLD"
  108. elif curChar == '{' and nextChar == '}':
  109. if mode is not None and mode != 'auto':
  110. # Invalid case 2: mixing automatic and manual field specifications -- example: "ABCD EFGH {name} IJKL {}", "Hello {vv} {}", "HELLO {0} WORLD {}"
  111. raise ValueError("Cannot switch from manual field numbering to automatic field specification")
  112. mode = 'auto'
  113. if(L<R): # Valid Case 2.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. tokens.append("{"+str(curArg)+"}") # Valid Case 2.2: add the special marker for the arg
  116. curArg+=1 # increment the arg position, this will be used for referencing the arg later
  117. L = R+2 # move the left pointer to the next char
  118. R = R+2 # move the right pointer to the next char
  119. continue
  120. # Valid Case 3: Key-word arg case: example: "ABCD EFGH {name} IJKL", "Hello {vv}", "HELLO {name} WORLD"
  121. elif (curChar == '{'):
  122. if mode is not None and mode != 'manual':
  123. # # Invalid case 2: mixing automatic and manual field specifications -- example: "ABCD EFGH {} IJKL {name}", "Hello {} {1}", "HELLO {} WORLD {name}"
  124. raise ValueError("Cannot switch from automatic field specification to manual field numbering")
  125. mode = 'manual'
  126. if(L<R): # Valid case 3.1: make sure we are not adding empty string
  127. tokens.append(s[L:R]) # add the string before the special marker for the arg
  128. # We look for the end of the keyword
  129. kwL = R # Keyword left pointer
  130. kwR = R+1 # Keyword right pointer
  131. while(kwR<len(s) and s[kwR]!='}'):
  132. if s[kwR] == '{': # Invalid case 3: stray '{' encountered, example: "ABCD EFGH {n{ame} IJKL {", "Hello {vv{}}", "HELLO {0} WOR{LD}"
  133. raise ValueError("Unexpected '{' in field name")
  134. kwR += 1
  135. # Valid case 3.2: We have successfully found the end of the keyword
  136. if kwR<len(s) and s[kwR] == '}':
  137. tokens.append(s[kwL:kwR+1]) # add the special marker for the arg
  138. L = kwR+1
  139. R = kwR+1
  140. # Invalid case 4: We didn't find the end of the keyword, throw error
  141. else:
  142. raise ValueError("Expected '}' before end of string")
  143. continue
  144. R = R+1
  145. # Valid case 4: We have reached the end of the string, add the remaining string to the tokens
  146. if L<R:
  147. tokens.append(s[L:R])
  148. # print(tokens)
  149. return tokens
  150. tokens = tokenizeString(self)
  151. argMap = {}
  152. for i, a in enumerate(args):
  153. argMap[str(i)] = a
  154. final_tokens = []
  155. for t in tokens:
  156. if t[0] == '{' and t[-1] == '}':
  157. key = t[1:-1]
  158. argMapVal = argMap.get(key, None)
  159. kwargsVal = kwargs.get(key, None)
  160. if argMapVal is None and kwargsVal is None:
  161. raise ValueError("No arg found for token: "+t)
  162. elif argMapVal is not None:
  163. final_tokens.append(str(argMapVal))
  164. else:
  165. final_tokens.append(str(kwargsVal))
  166. else:
  167. final_tokens.append(t)
  168. return ''.join(final_tokens)
  169. # if '{}' in self:
  170. # for i in range(len(args)):
  171. # self = self.replace('{}', str(args[i]), 1)
  172. # else:
  173. # # Positional arguments will be followed by keyword arguments
  174. # # 1. Replace the positional arguments
  175. # for i,a in enumerate(args):
  176. # self = self.replace('{'+str(i)+'}', str(a))
  177. # # 2. Replace the keyword arguments
  178. # for k,v in kwargs.items():
  179. # self = self.replace('{'+k+'}', str(v))
  180. # return self
  181. str.format = __f
  182. def __f(self, chars=None):
  183. chars = chars or ' \t\n\r'
  184. i = 0
  185. while i < len(self) and self[i] in chars:
  186. ++i
  187. return self[i:]
  188. str.lstrip = __f
  189. def __f(self, chars=None):
  190. chars = chars or ' \t\n\r'
  191. j = len(self) - 1
  192. while j >= 0 and self[j] in chars:
  193. --j
  194. return self[:j+1]
  195. str.rstrip = __f
  196. def __f(self, chars=None):
  197. chars = chars or ' \t\n\r'
  198. i = 0
  199. while i < len(self) and self[i] in chars:
  200. ++i
  201. j = len(self) - 1
  202. while j >= 0 and self[j] in chars:
  203. --j
  204. return self[i:j+1]
  205. str.strip = __f
  206. def __f(self, width: int):
  207. delta = width - len(self)
  208. if delta <= 0:
  209. return self
  210. return '0' * delta + self
  211. str.zfill = __f
  212. def __f(self, width: int, fillchar=' '):
  213. delta = width - len(self)
  214. if delta <= 0:
  215. return self
  216. assert len(fillchar) == 1
  217. return fillchar * delta + self
  218. str.rjust = __f
  219. def __f(self, width: int, fillchar=' '):
  220. delta = width - len(self)
  221. if delta <= 0:
  222. return self
  223. assert len(fillchar) == 1
  224. return self + fillchar * delta
  225. str.ljust = __f
  226. ##### list #####
  227. def __qsort(a: list, L: int, R: int, key):
  228. if L >= R: return;
  229. mid = a[(R+L)//2];
  230. mid = key(mid)
  231. i, j = L, R
  232. while i<=j:
  233. while key(a[i])<mid: ++i;
  234. while key(a[j])>mid: --j;
  235. if i<=j:
  236. a[i], a[j] = a[j], a[i]
  237. ++i; --j;
  238. __qsort(a, L, j, key)
  239. __qsort(a, i, R, key)
  240. def __f(self, reverse=False, key=None):
  241. if key is None:
  242. key = lambda x:x
  243. __qsort(self, 0, len(self)-1, key)
  244. if reverse:
  245. self.reverse()
  246. list.sort = __f
  247. def __f(self, other):
  248. for i, j in zip(self, other):
  249. if i != j:
  250. return i < j
  251. return len(self) < len(other)
  252. tuple.__lt__ = __f
  253. list.__lt__ = __f
  254. def __f(self, other):
  255. for i, j in zip(self, other):
  256. if i != j:
  257. return i > j
  258. return len(self) > len(other)
  259. tuple.__gt__ = __f
  260. list.__gt__ = __f
  261. def __f(self, other):
  262. for i, j in zip(self, other):
  263. if i != j:
  264. return i <= j
  265. return len(self) <= len(other)
  266. tuple.__le__ = __f
  267. list.__le__ = __f
  268. def __f(self, other):
  269. for i, j in zip(self, other):
  270. if i != j:
  271. return i >= j
  272. return len(self) >= len(other)
  273. tuple.__ge__ = __f
  274. list.__ge__ = __f
  275. type.__repr__ = lambda self: "<class '" + self.__name__ + "'>"
  276. type.__getitem__ = lambda self, *args: self # for generics
  277. def help(obj):
  278. if hasattr(obj, '__func__'):
  279. obj = obj.__func__
  280. print(obj.__signature__)
  281. print(obj.__doc__)
  282. del __f
  283. class Exception: pass
  284. from _long import long