File size: 2,006 Bytes
c40881f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2521b9
 
 
c40881f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
'''
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
'''