Spaces:
No application file
No application file
| ''' | |
| Write a function | |
| execute(code: str) -> str | |
| which takes a program written in your programming language as a parameter and returns the output of the program. | |
| At this point, the program must know the following commands: | |
| LET variable=value | |
| The command sets the value of the variable to the given integer. The variable is one of a, b, c or d - no other variable names are allowed. If the variable already has a value, the old value is overwritten. | |
| PRINT variable | |
| This command adds the value of the variable and the line break to the output. The value of the variable must be defined before it is printed. | |
| Three example programs for testing: | |
| LET a=10 | |
| PRINT a | |
| The program returns a printout | |
| 10 | |
| Program 2: | |
| LET a=100 | |
| LET b=200 | |
| PRINT a | |
| PRINT b | |
| The program returns the result: | |
| 100 | |
| 200 | |
| Program 3: | |
| LET c=10000 | |
| LET d=-10000 | |
| PRINT c | |
| PRINT d | |
| LET c=10 | |
| LET d=-10 | |
| PRINT c | |
| PRINT d | |
| The program returns the result: | |
| 10000 | |
| -10000 | |
| 10 | |
| -10 | |
| ''' | |
| # approach 1 | |
| def execute(code: str) -> str: | |
| variables = {'a': 0, 'b': 0, 'c': 0, 'd': 0} | |
| output = [] | |
| for line in code.split('\n'): | |
| line = line.strip() | |
| if line.startswith('LET'): | |
| _, assignment = line.split(' ', 1) | |
| var, value = assignment.split('=') | |
| if var in variables: | |
| variables[var] = int(value) | |
| else: | |
| raise ValueError(f"Invalid variable name: {var}") | |
| elif line.startswith('PRINT'): | |
| _, var = line.split() | |
| if var in variables: | |
| output.append(str(variables[var])) | |
| else: | |
| raise ValueError(f"Undefined variable: {var}") | |
| elif line: # Ignore empty lines | |
| raise ValueError(f"Invalid command: {line}") | |
| # return '\n'.join(output) | |
| for num in output: | |
| print(num) | |
| eg1='''LET a=10 | |
| PRINT a | |
| ''' | |
| execute(eg1) | |
| eg2='''LET a=100 | |
| LET b=200 | |
| PRINT a | |
| PRINT b | |
| ''' | |
| eg3='''LET c=10000 | |
| LET d=-10000 | |
| PRINT c | |
| PRINT d | |
| LET c=10 | |
| LET d=-10 | |
| PRINT c | |
| PRINT d | |
| ''' |