builtins.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 tokenize(s:str) -> list:
  87. tokens = []
  88. L, R = 0,0
  89. mode = None
  90. curPos = 0
  91. lookingForKword = False
  92. while(R<len(s) and not lookingForKword):
  93. curChar = s[R]
  94. nextChar = s[R+1] if R+1<len(s) else ''
  95. # Escaping case
  96. if (curChar == '{' and nextChar == '{') or (curChar == '}' and nextChar == '}'):
  97. tokens.append(curChar)
  98. L = R+2
  99. R = R+2
  100. continue
  101. # Regular command line arg case
  102. if curChar == '{' and nextChar == '}':
  103. if mode is not None and mode != 'auto':
  104. raise ValueError("Cannot switch from manual field numbering to automatic field specification")
  105. mode = 'auto'
  106. # best case {}, just for normal args
  107. if(L<R):
  108. tokens.append(s[L:R])
  109. tokens.append("{"+str(curPos)+"}")
  110. curPos+=1
  111. L = R+2
  112. R = R+2
  113. continue
  114. # Kwarg case
  115. elif (curChar == '{'):
  116. if mode is not None and mode != 'manual':
  117. raise ValueError("Cannot switch from automatic field specification to manual field numbering")
  118. mode = 'manual'
  119. if(L<R):
  120. tokens.append(s[L:R])
  121. lookingForKword = True
  122. kwL = R+1
  123. kwR = R+1
  124. while(kwR<len(s) and s[kwR]!='}'):
  125. kwR += 1
  126. tokens.append(s[R:kwR+1])
  127. if kwR<len(s) and s[kwR] == '}':
  128. lookingForKword = False
  129. L = kwR+1
  130. R = kwR+1
  131. continue
  132. R = R+1
  133. if lookingForKword:
  134. raise ValueError("Expected '}' before end of string")
  135. if(not lookingForKword and L<R):
  136. tokens.append(s[L:R])
  137. # print("Looking for kword: ", lookingForKword)
  138. return tokens
  139. def __f(self:str, *args, **kwargs) -> str:
  140. tokens = tokenize(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. # if '{}' in self:
  160. # for i in range(len(args)):
  161. # self = self.replace('{}', str(args[i]), 1)
  162. # else:
  163. # # Positional arguments will be followed by keyword arguments
  164. # # 1. Replace the positional arguments
  165. # for i,a in enumerate(args):
  166. # self = self.replace('{'+str(i)+'}', str(a))
  167. # # 2. Replace the keyword arguments
  168. # for k,v in kwargs.items():
  169. # self = self.replace('{'+k+'}', str(v))
  170. # return self
  171. str.format = __f
  172. def __f(self, chars=None):
  173. chars = chars or ' \t\n\r'
  174. i = 0
  175. while i < len(self) and self[i] in chars:
  176. ++i
  177. return self[i:]
  178. str.lstrip = __f
  179. def __f(self, chars=None):
  180. chars = chars or ' \t\n\r'
  181. j = len(self) - 1
  182. while j >= 0 and self[j] in chars:
  183. --j
  184. return self[:j+1]
  185. str.rstrip = __f
  186. def __f(self, chars=None):
  187. chars = chars or ' \t\n\r'
  188. i = 0
  189. while i < len(self) and self[i] in chars:
  190. ++i
  191. j = len(self) - 1
  192. while j >= 0 and self[j] in chars:
  193. --j
  194. return self[i:j+1]
  195. str.strip = __f
  196. def __f(self, width: int):
  197. delta = width - len(self)
  198. if delta <= 0:
  199. return self
  200. return '0' * delta + self
  201. str.zfill = __f
  202. def __f(self, width: int, fillchar=' '):
  203. delta = width - len(self)
  204. if delta <= 0:
  205. return self
  206. assert len(fillchar) == 1
  207. return fillchar * delta + self
  208. str.rjust = __f
  209. def __f(self, width: int, fillchar=' '):
  210. delta = width - len(self)
  211. if delta <= 0:
  212. return self
  213. assert len(fillchar) == 1
  214. return self + fillchar * delta
  215. str.ljust = __f
  216. ##### list #####
  217. def __qsort(a: list, L: int, R: int, key):
  218. if L >= R: return;
  219. mid = a[(R+L)//2];
  220. mid = key(mid)
  221. i, j = L, R
  222. while i<=j:
  223. while key(a[i])<mid: ++i;
  224. while key(a[j])>mid: --j;
  225. if i<=j:
  226. a[i], a[j] = a[j], a[i]
  227. ++i; --j;
  228. __qsort(a, L, j, key)
  229. __qsort(a, i, R, key)
  230. def __f(self, reverse=False, key=None):
  231. if key is None:
  232. key = lambda x:x
  233. __qsort(self, 0, len(self)-1, key)
  234. if reverse:
  235. self.reverse()
  236. list.sort = __f
  237. def __f(self, other):
  238. for i, j in zip(self, other):
  239. if i != j:
  240. return i < j
  241. return len(self) < len(other)
  242. tuple.__lt__ = __f
  243. list.__lt__ = __f
  244. def __f(self, other):
  245. for i, j in zip(self, other):
  246. if i != j:
  247. return i > j
  248. return len(self) > len(other)
  249. tuple.__gt__ = __f
  250. list.__gt__ = __f
  251. def __f(self, other):
  252. for i, j in zip(self, other):
  253. if i != j:
  254. return i <= j
  255. return len(self) <= len(other)
  256. tuple.__le__ = __f
  257. list.__le__ = __f
  258. def __f(self, other):
  259. for i, j in zip(self, other):
  260. if i != j:
  261. return i >= j
  262. return len(self) >= len(other)
  263. tuple.__ge__ = __f
  264. list.__ge__ = __f
  265. type.__repr__ = lambda self: "<class '" + self.__name__ + "'>"
  266. type.__getitem__ = lambda self, *args: self # for generics
  267. def help(obj):
  268. if hasattr(obj, '__func__'):
  269. obj = obj.__func__
  270. print(obj.__signature__)
  271. print(obj.__doc__)
  272. del __f
  273. class Exception: pass
  274. from _long import long