Write a python class Const, Square, Print so that I can write, for example, Cost(5) >> Square() >> Inc() >> Inc() >> Print() and the resulting python program will print 27 to the screen.
Write a python class Const, Square, Print so that I can write, for example, Cost(5) >> Square() >> Inc() >> Inc() >> Print() and the resulting python program will print 27 to the screen.
To achieve the desired functionality, we can create a series of classes that allow for method chaining. Each class will perform a specific operation and return an instance of the next class in the chain. Here's how you can implement it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Const: def __init__(self, value): self.value = value def __rshift__(self, other): return other.process(self.value) class Square: def process(self, value): self.value = value ** 2 return self def __rshift__(self, other): return other.process(self.value) class Inc: def process(self, value): self.value = value + 1 return self def __rshift__(self, other): return other.process(self.value) class Print: def process(self, value): print(value) # Example usage: Const(5) >> Square() >> Inc() >> Inc() >> Print() |
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Const: def __init__(self, value): self.value = value def __rshift__(self, other): return other.process(self.value) class Square: def process(self, value): self.value = value ** 2 return self def __rshift__(self, other): return other.process(self.value) class Inc: def process(self, value): self.value = value + 1 return self def __rshift__(self, other): return other.process(self.value) class Print: def process(self, value): print(value) # Example usage: Const(5) >> Square() >> Inc() >> Inc() >> Print() |
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | class Const: def __init__(self, value): self.value = value def __rshift__(self, other): return other.process(self.value) class Square: def process(self, value): self.value = value ** 2 return self def __rshift__(self, other): return other.process(self.value) class Inc: def process(self, value): self.value = value + 1 return self def __rshift__(self, other): return other.process(self.value) class Print: def process(self, value): print(value) # Example usage: Const(5) >> Square() >> Inc() >> Inc() >> Print() answer = Const(2) >> Square() >> Inc() >> Square() >> Square() >> Print() expected = 0 assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' print('All tests passed') |
27
625
Traceback (most recent call last):
File "/usr/src/app/main.py", line 38, in <module>
assert answer == expected, f'Wrong answer; got {answer} instead of {expected}'
^^^^^^^^^^^^^^^^^^
AssertionError: Wrong answer; got None instead of 0
Testing if the previous output contains the string 625
: True