KaiquanMah commited on
Commit
c40881f
·
verified ·
1 Parent(s): c3d4cac

Create 18. Own programming language, Part 1

Browse files
Week 7 Libraries and More Python/18. Own programming language, Part 1 ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Write a function
3
+
4
+ execute(code: str) -> str
5
+
6
+ which takes a program written in your programming language as a parameter and returns the output of the program.
7
+
8
+
9
+
10
+
11
+ At this point, the program must know the following commands:
12
+
13
+ LET variable=value
14
+ 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.
15
+
16
+
17
+
18
+ PRINT variable
19
+ 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.
20
+
21
+
22
+
23
+
24
+
25
+
26
+ Three example programs for testing:
27
+
28
+ LET a=10
29
+ PRINT a
30
+ The program returns a printout
31
+ 10
32
+
33
+
34
+
35
+ Program 2:
36
+ LET a=100
37
+ LET b=200
38
+ PRINT a
39
+ PRINT b
40
+ The program returns the result:
41
+ 100
42
+ 200
43
+
44
+
45
+
46
+ Program 3:
47
+ LET c=10000
48
+ LET d=-10000
49
+ PRINT c
50
+ PRINT d
51
+ LET c=10
52
+ LET d=-10
53
+ PRINT c
54
+ PRINT d
55
+ The program returns the result:
56
+ 10000
57
+ -10000
58
+ 10
59
+ -10
60
+ '''
61
+
62
+
63
+
64
+
65
+
66
+ # approach 1
67
+ def execute(code: str) -> str:
68
+ variables = {'a': 0, 'b': 0, 'c': 0, 'd': 0}
69
+ output = []
70
+
71
+ for line in code.split('\n'):
72
+ line = line.strip()
73
+ if line.startswith('LET'):
74
+ _, assignment = line.split(' ', 1)
75
+ var, value = assignment.split('=')
76
+ if var in variables:
77
+ variables[var] = int(value)
78
+ else:
79
+ raise ValueError(f"Invalid variable name: {var}")
80
+ elif line.startswith('PRINT'):
81
+ _, var = line.split()
82
+ if var in variables:
83
+ output.append(str(variables[var]))
84
+ else:
85
+ raise ValueError(f"Undefined variable: {var}")
86
+ elif line: # Ignore empty lines
87
+ raise ValueError(f"Invalid command: {line}")
88
+
89
+ return '\n'.join(output)
90
+
91
+
92
+
93
+ eg1='''LET a=10
94
+ PRINT a
95
+ '''
96
+ execute(eg1)
97
+
98
+ eg2='''LET a=100
99
+ LET b=200
100
+ PRINT a
101
+ PRINT b
102
+ '''
103
+
104
+ eg3='''LET c=10000
105
+ LET d=-10000
106
+ PRINT c
107
+ PRINT d
108
+ LET c=10
109
+ LET d=-10
110
+ PRINT c
111
+ PRINT d
112
+ '''