fork download
  1. #!/usr/bin/env python3
  2.  
  3. import sys
  4. from random import randint
  5.  
  6. # メッセージ分離方式
  7. msg = {'cont': 'continue?[y/n] ',
  8. 'prompt': 'Type a guess: ',
  9. 'l': 'lower',
  10. 'u': 'upper',
  11. None: ''}
  12.  
  13. # 環境
  14. class Env(object):
  15. __match_args__ = ('secret_num', 'boolean', 'count', 'key')
  16. def __init__(self, secret_num, boolean = False, count = 0, key = None):
  17. self.secret_num = secret_num
  18. self.boolean = boolean
  19. self.count = count
  20. self.key = key
  21. # デバッグ用
  22. def __repr__(self):
  23. return f'<secret_num: {self.secret_num} boolean: {self.boolean} count: {self.count} key: {self.key}>'
  24.  
  25. # 環境の初期化
  26. def init():
  27. return Env(randint(1, 100))
  28.  
  29. # Read(読み込み部)
  30. def read(env):
  31. proc = {True: lambda x: x.lower() == 'y', False: int}
  32. key = {True: 'cont', False: 'prompt'}
  33. return proc[env.boolean](input(msg[key[env.boolean]]))
  34.  
  35. # Evaluator(評価器)
  36. def interp(x, env):
  37. match env:
  38. case Env(secret_num, boolean, count, key):
  39. if boolean:
  40. if x:
  41. return init()
  42. else:
  43. sys.exit()
  44. else:
  45. return Env(secret_num,
  46. x == secret_num,
  47. count + 1,
  48. 'l' if x > secret_num else 'u')
  49.  
  50. # Print(出力部)
  51. def display(env):
  52. match env:
  53. case Env(secret_num, boolean, count, key):
  54. print(count if boolean else msg[key])
  55. return env
  56.  
  57. # 端末で起動する
  58. if __name__ == '__main__':
  59. # 環境の初期化
  60. env = init()
  61. # Read-Eval-Print Loop(REPL)
  62. while True:
  63. env = display(interp(read(env), env))
  64.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Traceback (most recent call last):
  File "/usr/lib/python3.9/py_compile.py", line 144, in compile
    code = loader.source_to_code(source_bytes, dfile or file,
  File "<frozen importlib._bootstrap_external>", line 918, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "./prog.py", line 37
    match env:
          ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.9/py_compile.py", line 150, in compile
    raise py_exc
py_compile.PyCompileError:   File "./prog.py", line 37
    match env:
          ^
SyntaxError: invalid syntax

stdout
Standard output is empty