builtins.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. #pragma once
  2. const char* __BUILTINS_CODE = R"(
  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 round(x, ndigits=0):
  7. assert ndigits >= 0
  8. if ndigits == 0:
  9. return x >= 0 ? int(x + 0.5) : int(x - 0.5)
  10. if x >= 0:
  11. return int(x * 10**ndigits + 0.5) / 10**ndigits
  12. else:
  13. return int(x * 10**ndigits - 0.5) / 10**ndigits
  14. def isinstance(obj, cls):
  15. assert type(cls) is type
  16. obj_t = type(obj)
  17. while obj_t is not None:
  18. if obj_t is cls:
  19. return True
  20. obj_t = obj_t.__base__
  21. return False
  22. def abs(x):
  23. return x < 0 ? -x : x
  24. def max(a, b):
  25. return a > b ? a : b
  26. def min(a, b):
  27. return a < b ? a : b
  28. def sum(iterable):
  29. res = 0
  30. for i in iterable:
  31. res += i
  32. return res
  33. def map(f, iterable):
  34. return [f(i) for i in iterable]
  35. def zip(a, b):
  36. return [(a[i], b[i]) for i in range(min(len(a), len(b)))]
  37. def reversed(iterable):
  38. a = list(iterable)
  39. return [a[i] for i in range(len(a)-1, -1, -1)]
  40. def sorted(iterable, key=None, reverse=False):
  41. if key is None:
  42. key = lambda x: x
  43. a = [key(i) for i in iterable]
  44. b = list(iterable)
  45. for i in range(len(a)):
  46. for j in range(i+1, len(a)):
  47. if (a[i] > a[j]) ^ reverse:
  48. a[i], a[j] = a[j], a[i]
  49. b[i], b[j] = b[j], b[i]
  50. return b
  51. ##### str #####
  52. str.__mul__ = lambda self, n: ''.join([self for _ in range(n)])
  53. def __str4split(self, sep):
  54. if sep == "":
  55. return list(self)
  56. res = []
  57. i = 0
  58. while i < len(self):
  59. if self[i:i+len(sep)] == sep:
  60. res.append(self[:i])
  61. self = self[i+len(sep):]
  62. i = 0
  63. else:
  64. i += 1
  65. res.append(self)
  66. return res
  67. str.split = __str4split
  68. del __str4split
  69. def __str4index(self, sub):
  70. for i in range(len(self)):
  71. if self[i:i+len(sub)] == sub:
  72. return i
  73. return -1
  74. str.index = __str4index
  75. del __str4index
  76. def __str4strip(self, chars=None):
  77. chars = chars or ' \t\n\r'
  78. i = 0
  79. while i < len(self) and self[i] in chars:
  80. i += 1
  81. j = len(self) - 1
  82. while j >= 0 and self[j] in chars:
  83. j -= 1
  84. return self[i:j+1]
  85. str.strip = __str4strip
  86. del __str4strip
  87. ##### list #####
  88. list.__repr__ = lambda self: '[' + ', '.join([repr(i) for i in self]) + ']'
  89. tuple.__repr__ = lambda self: '(' + ', '.join([repr(i) for i in self]) + ')'
  90. list.__json__ = lambda self: '[' + ', '.join([i.__json__() for i in self]) + ']'
  91. tuple.__json__ = lambda self: '[' + ', '.join([i.__json__() for i in self]) + ']'
  92. def __list4extend(self, other):
  93. for i in other:
  94. self.append(i)
  95. list.extend = __list4extend
  96. del __list4extend
  97. def __list4remove(self, value):
  98. for i in range(len(self)):
  99. if self[i] == value:
  100. del self[i]
  101. return True
  102. return False
  103. list.remove = __list4remove
  104. del __list4remove
  105. def __list4index(self, value):
  106. for i in range(len(self)):
  107. if self[i] == value:
  108. return i
  109. return -1
  110. list.index = __list4index
  111. del __list4index
  112. def __list4pop(self, i=-1):
  113. res = self[i]
  114. del self[i]
  115. return res
  116. list.pop = __list4pop
  117. del __list4pop
  118. def __list4__mul__(self, n):
  119. a = []
  120. for i in range(n):
  121. a.extend(self)
  122. return a
  123. list.__mul__ = __list4__mul__
  124. del __list4__mul__
  125. def __iterable4__eq__(self, other):
  126. if len(self) != len(other):
  127. return False
  128. for i in range(len(self)):
  129. if self[i] != other[i]:
  130. return False
  131. return True
  132. list.__eq__ = __iterable4__eq__
  133. tuple.__eq__ = __iterable4__eq__
  134. list.__ne__ = lambda self, other: not self.__eq__(other)
  135. tuple.__ne__ = lambda self, other: not self.__eq__(other)
  136. del __iterable4__eq__
  137. def __iterable4count(self, x):
  138. res = 0
  139. for i in self:
  140. if i == x:
  141. res += 1
  142. return res
  143. list.count = __iterable4count
  144. tuple.count = __iterable4count
  145. del __iterable4count
  146. def __iterable4__contains__(self, item):
  147. for i in self:
  148. if i == item:
  149. return True
  150. return False
  151. list.__contains__ = __iterable4__contains__
  152. tuple.__contains__ = __iterable4__contains__
  153. del __iterable4__contains__
  154. list.__new__ = lambda obj: [i for i in obj]
  155. # https://github.com/python/cpython/blob/main/Objects/dictobject.c
  156. class dict:
  157. def __init__(self, capacity=16):
  158. self._capacity = capacity
  159. self._a = [None] * self._capacity
  160. self._len = 0
  161. def __len__(self):
  162. return self._len
  163. def __probe(self, key):
  164. i = hash(key) % self._capacity
  165. while self._a[i] is not None:
  166. if self._a[i][0] == key:
  167. return True, i
  168. i = (i + 1) % self._capacity
  169. return False, i
  170. def __getitem__(self, key):
  171. ok, i = self.__probe(key)
  172. if not ok:
  173. raise KeyError(key)
  174. return self._a[i][1]
  175. def __contains__(self, key):
  176. ok, i = self.__probe(key)
  177. return ok
  178. def __setitem__(self, key, value):
  179. ok, i = self.__probe(key)
  180. if ok:
  181. self._a[i][1] = value
  182. else:
  183. self._a[i] = [key, value]
  184. self._len += 1
  185. if self._len > self._capacity * 0.8:
  186. self._capacity *= 2
  187. self.__rehash()
  188. def __delitem__(self, key):
  189. ok, i = self.__probe(key)
  190. if not ok:
  191. raise KeyError(key)
  192. self._a[i] = None
  193. self._len -= 1
  194. def __rehash(self):
  195. old_a = self._a
  196. self._a = [None] * self._capacity
  197. self._len = 0
  198. for kv in old_a:
  199. if kv is not None:
  200. self[kv[0]] = kv[1]
  201. def keys(self):
  202. return [kv[0] for kv in self._a if kv is not None]
  203. def values(self):
  204. return [kv[1] for kv in self._a if kv is not None]
  205. def items(self):
  206. return [kv for kv in self._a if kv is not None]
  207. def clear(self):
  208. self._a = [None] * self._capacity
  209. self._len = 0
  210. def update(self, other):
  211. for k, v in other.items():
  212. self[k] = v
  213. def copy(self):
  214. d = dict()
  215. for kv in self._a:
  216. if kv is not None:
  217. d[kv[0]] = kv[1]
  218. return d
  219. def __repr__(self):
  220. a = [repr(k)+': '+repr(v) for k,v in self.items()]
  221. return '{'+ ', '.join(a) + '}'
  222. def __json__(self):
  223. a = []
  224. for k,v in self.items():
  225. if type(k) is not str:
  226. raise TypeError('json keys must be strings, got ' + repr(k) )
  227. a.append(k.__json__()+': '+v.__json__())
  228. return '{'+ ', '.join(a) + '}'
  229. class set:
  230. def __init__(self, iterable=None):
  231. iterable = iterable or []
  232. self._a = dict()
  233. for item in iterable:
  234. self.add(item)
  235. def add(self, elem):
  236. self._a[elem] = None
  237. def discard(self, elem):
  238. if elem in self._a:
  239. del self._a[elem]
  240. def remove(self, elem):
  241. del self._a[elem]
  242. def clear(self):
  243. self._a.clear()
  244. def update(self,other):
  245. for elem in other:
  246. self.add(elem)
  247. return self
  248. def __len__(self):
  249. return len(self._a)
  250. def copy(self):
  251. return set(self._a.keys())
  252. def __and__(self, other):
  253. ret = set()
  254. for elem in self:
  255. if elem in other:
  256. ret.add(elem)
  257. return ret
  258. def __or__(self, other):
  259. ret = self.copy()
  260. for elem in other:
  261. ret.add(elem)
  262. return ret
  263. def __sub__(self, other):
  264. ret = set()
  265. for elem in self:
  266. if elem not in other:
  267. ret.add(elem)
  268. return ret
  269. def __xor__(self, other):
  270. ret = set()
  271. for elem in self:
  272. if elem not in other:
  273. ret.add(elem)
  274. for elem in other:
  275. if elem not in self:
  276. ret.add(elem)
  277. return ret
  278. def union(self, other):
  279. return self | other
  280. def intersection(self, other):
  281. return self & other
  282. def difference(self, other):
  283. return self - other
  284. def symmetric_difference(self, other):
  285. return self ^ other
  286. def __eq__(self, other):
  287. return self.__xor__(other).__len__() == 0
  288. def __ne__(self, other):
  289. return self.__xor__(other).__len__() != 0
  290. def isdisjoint(self, other):
  291. return self.__and__(other).__len__() == 0
  292. def issubset(self, other):
  293. return self.__sub__(other).__len__() == 0
  294. def issuperset(self, other):
  295. return other.__sub__(self).__len__() == 0
  296. def __contains__(self, elem):
  297. return elem in self._a
  298. def __repr__(self):
  299. if len(self) == 0:
  300. return 'set()'
  301. return '{'+ ', '.join(self._a.keys()) + '}'
  302. def __iter__(self):
  303. return self._a.keys().__iter__()
  304. )";
  305. const char* __RANDOM_CODE = R"(
  306. import time as _time
  307. __all__ = ['Random', 'seed', 'random', 'randint', 'uniform']
  308. def _int32(x):
  309. return int(0xffffffff & x)
  310. class Random:
  311. def __init__(self, seed=None):
  312. if seed is None:
  313. seed = int(_time.time() * 1000000)
  314. seed = _int32(seed)
  315. self.mt = [0] * 624
  316. self.mt[0] = seed
  317. self.mti = 0
  318. for i in range(1, 624):
  319. self.mt[i] = _int32(1812433253 * (self.mt[i - 1] ^ self.mt[i - 1] >> 30) + i)
  320. def extract_number(self):
  321. if self.mti == 0:
  322. self.twist()
  323. y = self.mt[self.mti]
  324. y = y ^ y >> 11
  325. y = y ^ y << 7 & 2636928640
  326. y = y ^ y << 15 & 4022730752
  327. y = y ^ y >> 18
  328. self.mti = (self.mti + 1) % 624
  329. return _int32(y)
  330. def twist(self):
  331. for i in range(0, 624):
  332. y = _int32((self.mt[i] & 0x80000000) + (self.mt[(i + 1) % 624] & 0x7fffffff))
  333. self.mt[i] = (y >> 1) ^ self.mt[(i + 397) % 624]
  334. if y % 2 != 0:
  335. self.mt[i] = self.mt[i] ^ 0x9908b0df
  336. def seed(self, x):
  337. assert type(x) is int
  338. self.mt = [0] * 624
  339. self.mt[0] = _int32(x)
  340. self.mti = 0
  341. for i in range(1, 624):
  342. self.mt[i] = _int32(1812433253 * (self.mt[i - 1] ^ self.mt[i - 1] >> 30) + i)
  343. def random(self):
  344. return self.extract_number() / 2 ** 32
  345. def randint(self, a, b):
  346. assert type(a) is int and type(b) is int
  347. assert a <= b
  348. return int(self.random() * (b - a + 1)) + a
  349. def uniform(self, a, b):
  350. assert type(a) is int or type(a) is float
  351. assert type(b) is int or type(b) is float
  352. if a > b:
  353. a, b = b, a
  354. return self.random() * (b - a) + a
  355. def shuffle(self, L):
  356. for i in range(len(L)):
  357. j = self.randint(i, len(L) - 1)
  358. L[i], L[j] = L[j], L[i]
  359. def choice(self, L):
  360. return L[self.randint(0, len(L) - 1)]
  361. _inst = Random()
  362. seed = _inst.seed
  363. random = _inst.random
  364. randint = _inst.randint
  365. uniform = _inst.uniform
  366. shuffle = _inst.shuffle
  367. choice = _inst.choice
  368. )";