L4K ︰ 通往 Python 的道路 ── GvR 的一堂課

一十八步說分明,步步講解致其功︰

The Roger Frank Lessons
Introduction to Computer Science: GvR Unit

Programming with GvR

Programming a computer in a language like Python requires a precise sequencing of steps written in a language where details of syntax can be overwhelming for a beginner. Everything must be exactly right, and errors in just getting the program to run are frustrating. Often the output of beginning computer programs are text-based and uninteresting, at least to humans.

To get acquainted with the concepts of computing without getting bogged down in the syntax of a higher-level language such as Python, we begin by programming Guido van Robot. GvR is a teaching tool that presents the concepts in a visual way using a robot-language that is simple, yet powerful and extensible.

We program Guido, a simple robot that lives in a simple world. Because Guido and his world are a visual simulation, we can watch the effects of our programming statements. This activity is presented in a series of steps — tutorials with accompanying mini-labs.

Step 1 Guido’s First Steps creating .wld and .gvr files
Step 2 What’s That Sound? beepers
Step 3 Turn, Turn, Turn sequential instructions
Step 4 Just Another Brick in the Wall world file: walls
Step 5 Do The Right Thing user-generated instruction
Step 6 Robotics Times Project
Step 7 Birthday Message Project
Step 8 Decisions if statement
Step 9 You Missed Some do statement
Step 10 Let’s Dance nested user instructions
Step 11 Apple Pie or Cookies? if..elif..else statement
Step 12 Take Out the Trash Conditional Looping
Step 13 World Traveler Project
Step 14 It’s Going to Rain Project
Step 15 A Job to Do Project
Step 16 Lunchbox Project
Step 17 Community Service Revisted Project
Step 18 Where to Go from Here… Conclusion

Acknowledgements

This series of Guido van Robot exercises was written by Roger Frank. Comments and suggestions about these lessons should be sent to Jeffrey Elkner, who converted them from Roger’s Karel the Robot originals and who currently maintains them.

The Guido van Robot programming language is descended from two parent languages: Karel the Robot and Python. Karel the Robot was introduced by Richard Pattis in his book Karel the Robot: A Gentle Introduction to the Art of Programming with Pascal, John Wiley & Sons, Inc., 1981. Python is the creation of Guido van Rossum and members of the Python community. Information on Python can be found at: http://www.python.org

GvR was developed by high school computer science students at Yorktown High School in Arlington, VA, under guidance of mentor Steve Howell.

 

假使母語啟童蒙,編寫派生一路通︰

生 ︰以蠡難以測海,欲明程式語言之 秘 秘,須知那 元 元語言之『理』,需究這 組 組織之『則』,如是雖 秘 秘,終非 密 密不透風,有所遇之哉!!

Toy Parser Generator

abstract

Toy Parser Generator is a lexical and syntactic parser generator for Python. This generator was born from a simple statement: YACC is too complex to use in simple cases (calculators, configuration files, small programming languages, …).

TPG can very simply write parsers that are usefull for most every day needs (even if it can’t make your coffee). With a very clear and simple syntax, you can write an attributed grammar that is translated into a recursive descendant parser. TPG generated code is very closed to the original grammar. This means that the parser works like the grammar. A grammar rule can be seen as a method of the parser class, symbols as method calls, attributes as method parameters and semantic values as return values. You can also add Python code directly into grammar rules and build abstract syntax trees while parsing.

The first application of TPG is TPG itself. The first (not released) version of TPG has been written by hand then was used to generate next versions. Now TPG can generate itself.

For an uptodate documentation, please read tpg.pdf.

Please let me know if you use TPG in one of your projects. I will add you in the list of projects using TPG.

△ TPG 派生三之安裝︰

wget http://cdsoft.fr/tpg/TPG-3.2.2.tar.gz
tar -zxvf TPG-3.2.2.tar.gz
cd TPG-3.2.2/
sudo python3 setup.py install

 

碼 ︰家 習 。請閱讀 tpg.pdf 文件,試將下面程式中文化,比方『 + 』改作『加』,『 * 』變為『乘』,…『 sqrt 』譯釋成『根號』。會心『俚語』,根號 179 之所指。

#!/usr/bin/env python

import math
import operator
import string
import tpg

if tpg.__python__ == 3:
    operator.div = operator.truediv
    raw_input = input

def make_op(op):
    return {
        '+'   : operator.add,
        '-'   : operator.sub,
        '*'   : operator.mul,
        '/'   : operator.div,
        '%'   : operator.mod,
        '^'   : lambda x,y:x**y,
        '**'  : lambda x,y:x**y,
        'cos' : math.cos,
        'sin' : math.sin,
        'tan' : math.tan,
        'acos': math.acos,
        'asin': math.asin,
        'atan': math.atan,
        'sqr' : lambda x:x*x,
        'sqrt': math.sqrt,
        'abs' : abs,
        'norm': lambda x,y:math.sqrt(x*x+y*y),
    }[op]

class Calc(tpg.Parser, dict):
    r"""
        separator space '\s+' ;

        token pow_op    '\^|\*\*'                                              token add_op    '[+-]'
        token mul_op    '[*/%]'                                                token funct1    '(cos|sin|tan|acos|asin|atan|sqr|sqrt|abs)\b'
        token funct2    '(norm)\b'                                             token real      '(\d+\.\d*|\d*\.\d+)([eE][-+]?\d+)?|\d+[eE][-+]?\d+'
        token integer   '\d+'                                                  token VarId     '[a-zA-Z_]\w*'

        START/e ->
                'vars'                  e=self.mem()             |   VarId/v '=' Expr/e self[v]=e
            |   Expr/e
        ;

        Var/self.get(v,0) -> VarId/v ;

        Expr/e -> Term/e ( add_op/op Term/t     e=op(e,t)                          )*         ;          Term/t -> Fact/t ( mul_op/op Fact/f t=op(t,f)
                         )*
        ;

        Fact/f ->
                add_op/op Fact/f                f=op(0,f)             |   Pow/f         ;          Pow/f -> Atom/f ( pow_op/op Fact/e f=op(f,e)
                        )?
        ;

        Atom/a ->
                real/a
            |   integer/a
            |   Function/a
            |   Var/a
            |   '' Expr/a ''
        ;

        Function/y ->
                funct1/f '' Expr/x ''               y = f(x)             |   funct2/f '<img src="http://www.freesandal.org/wp-content/ql-cache/quicklatex.com-5618a7a7b23dfd84e41ef622fed8142e_l3.png" class="ql-img-inline-formula quicklatex-auto-format" alt="' Expr/x1 ',' Expr/x2 '" title="Rendered by QuickLaTeX.com" height="19" width="165" style="vertical-align: -5px;"/>' y = f(x1,x2)
        ;

    """

    def mem(self):
        vars = sorted(self.items())
        memory = [ "%s = %s"%(var, val) for (var, val) in vars ]
        return "\n\t" + "\n\t".join(memory)

print("Calc (TPG example)")
calc = Calc()
while 1:
    l = raw_input("\n:")
    if l:
        try:
            print(calc(l))
        except Exception:
            print(tpg.exc())
    else:
        break

 

行 ︰  文件總長四十七,真真是『杞』小『瓜』大,什麼也沒說,就要人家『以杞包瓜』。還會心『根號一七九』的哩!不知要不要四捨五入,小數點下有幾位,分明是罵人!!☿☹☹

 

訊 ︰☿ 后 后,上古之女王也。何時起加了個 女 女,就成了姤,祇知求『遇偶』,真不曉『後起者』造字是何肚腸??

── 摘自《M♪o 之學習筆記本《辰》組元︰【䷫】以杞包瓜