Update page 'Day2 Homework -Karen'

2023-03-31 17:58:53 +02:00
parent a3e97c2493
commit 862c036efb
+51 -1
@@ -79,12 +79,62 @@ Comparison table for complex literals:
**4. Write a small program that uses the AST module to open the lexer/parser example, and dumps the resulting AST. See if there are any arguments to the parse method which make the output easier to read.** **4. Write a small program that uses the AST module to open the lexer/parser example, and dumps the resulting AST. See if there are any arguments to the parse method which make the output easier to read.**
Maybe we can first write a simple lexer sample, and then import `astor` module to output the AST in a more human-readable format.
```
import ply.lex as lex
# Define the list of token names
tokens = (
'NUMBER',
'PLUS',
'MINUS'
)
# Define the regular expressions for each token
t_PLUS = r'\+'
t_MINUS = r'-'
t_NUMBER = r'\d+'
# Define a rule to handle whitespace
def t_whitespace(t):
r'\s+'
pass
# Define a rule to handle errors
def t_error(t):
print("Invalid character '%s'" % t.value[0])
t.lexer.skip(1)
# Create the lexer
lexer = lex.lex()
# Test the lexer on a sample input
input_str = "3 + 4 * (2 - 1)"
lexer.input(input_str)
for token in lexer:
print(token.type, token.value)
import ast
import astor
tree = ast.parse(input_str)
print(astor.to_source(tree))
```
**5. What does this do? `print("\007")` Can you figure out why?** **5. What does this do? `print("\007")` Can you figure out why?**
It prints an ASCII bell character to the console, and it is used to produce an audible signal. The character is interpreted by the computer's terminal or console to produce a beep or flashing effect, typically used to alert something.
**6. What does this do? `print("abcdefg\rhijklmnop")` Can you figure out why?**
The `\r` character in the string is used to instructs the console to return the cursor to the beginning of the current line without advancing to the next line, so in this case, it will prints the string "hijklmnop" over the string "abcdefg" in the console, replacing the first seven characters of the first string with the second string.
```
>>> print("abcdefg\rhijklmnop")
hijklmnop
```
**6. What does this do? `print("abcdefg\rhijklmnop")` Can you figure out why?**
**7. This is an HTTP server. Run it and connect to http://localhost:8000 . Why doesn't this do the same thing as what you see above? (don't forget to shut down the HTTP server afterward.)** **7. This is an HTTP server. Run it and connect to http://localhost:8000 . Why doesn't this do the same thing as what you see above? (don't forget to shut down the HTTP server afterward.)**