builtins.py 8.1 KB

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