parsing tree

hello my luft ballons
[(“word-element”, “hello”),
(“word-element”,”my”),
(“javascript-element”), “document.write(99);”)
(“word-elment”, “luftballons”),
]

def interpret(trees):
	for tree in trees:
		treetype = tree[0]
		if treetype == "word-element":
			graphics.word(node[1])
		elif treetype == "javascript-element":
			jstext = tree[1]
			jslexer = lex.lex(module=jstokens)
			jsparser = yacc.yacc(module=jsgrammar)
			jstree = jsparser.parse(jstext,lexer=jslexer)
			result = jsinterp.interpret( jstree )
			graphics.word( result )
def env_lookup(vname, env):
	if vname in env[1]:
		return (env[1])[vname]
	elif env[0] == None:
		return None
	else:
		return env_lookup(vname, env[0])
var a = 1;
function mistletue(baldr){
	baldr = baldr + 1;
	a = a + 2;
	baldr = baldr + a;
	return baldr;
}
write (mistletue(5));
def optimize(tree):
	etype = tree[0]
	if etype == "binop":
		a = tree[1]
		op = tree[2]
		b = tree[3]
		if op == "*" and b == ("number","1"):
			return a
		return tree
def remove_html_markup(s):
	tag = False
	out = ""

	for c in s:
		if c == '<':
			tag = True
		elif c == '>':
			tag = False
		elif not tag:
			out = out + c

	return out
print remove_html_markup("<b>foo</b>")

fibo

def fibo(n):
	in n <= 2:
		return 1
	else:
		return fibo(n-1)+fibo(n-2)

print fibo(20)
&#91;/python&#93;

&#91;python&#93;
chart = {}

def memofibo(n):
    if n in chart:
    	return chart&#91;n&#93;
    elif n <= 2:
    	chart&#91;n&#93; = 1
    
print memofibo(24)
&#91;/python&#93;

&#91;python&#93;
def t_javascript(token):
	r'<script\ type=\"text\/javascript\"\>'
	token.lexer.code_start = token.lexer.lexpos
	token.lexer.begin("javascript")

def t_javascript_end(token):
def t_javascript(token):
	r'<script\ type=\"text\/javascript\"\>'
	token.lexer.code_start = token.lexer.lexpos
	token.lexer.begin("javascript")

def t_javascript_end(token):
	r'\<\/script\>'
	token.value = token.lexer.lexdata[token.lexer.code_start:
		token.lexer.lexpos-9]
	token.type = 'JAVASCRIPT'
	token.lexer.lineno += token.value.count('\n')
	token.lexer.begin.('INITIAL')
	return token

parthing:構文解析 lexing:字句解析
after regular expression, lexer get token value.

javascript to python

#        function mymin(a, b){
#            if (a < b){
#                return a;
#            } else {
#                return b;
#            };
#        }
#        
#        function square(x){
#            return x * x;
#        }
#        
#        write(mymin(square(-2), square(3)));

def mymin(a, b):
	if (a < b):
		return a
	else:
		return b

def square(x):
	return x * x
print mymin(square(-2), square(3))
[1,2,3,4,5,6,7]

def odds_only(numbers):
	for N in numbers:
		if N % 2 == 1:
			yield N
def small_words(words):
	for word in words:
		if len(word) <= 3:
			yield word

print [w for w in small_words(["The","quick","brown","fox"])]
grammar = [
	("exp",["exp","+","exp"]),
	("exp",["exp","-","exp"]),
	("exp",["(","exp",")"]),
	("exp",["num"]),
]

def expand(tokens, grammar):
	for pos in range(len(tokens)):
		for rule in grammar:

depth = 1
utterances = [["exp"]]
def sublists(big_list, selected_so_far):
	if big_list == []:
		print selected_so_far
	else:
		current_element = big_list[0]
		rest_of_big_list = big_list[1:]
		sublists(rest_of_big_list, selected_so_far + [current_element])
		sublists(rest_of_big_list, selected_so_far )

	dinner_guests = ["LM", "ECS", "SBA"]
	sublists(dinner_guests, [])
def cfgempty(grammar, symbol, visited):
	if symbol in visited:
		return None
	elif not any([rule[0] == symbol for rule in grammar ]):
		return [symbol]
	else:
		new_visited = visited + [symbol]
		for rhs in [r[1] for r in grammar if r[0] == symbol]:
			if all([None] != cfgempty(frammar, r, new_visited) for r in rhs):
				result = []
				for r in rhs:
					result = result + cfgempty(grammar, r, new_visited)
				return result
		return None

JS Number

tokens = (
	'IDENTIFIER',
	'NUMBER',
	'STRING'
	)

def t_NUMBER(t):
	r'-?[0-9]+(?:\.[0-9]*)?'
	t.value = float(t.value)
	return t

def t_STRING(t):
	r'([^"\\]|(\\.))*"'
	t.value = t.value[1:-1]
	return t
function gcd(a,b){
	if(a==b){
		return a;
	} else {
		if(a > b){
		return gcd(a-b, b);
		} else {
			return gcd(a, b- a)
		}
	}
}

recursion: function call itself

javascript and python

def uptoten(x):
if x < 10: return x else: return 10 javascriptcode=""" function uptoten(x) { if x < 10 { return x } else { return 10 } } """ [/python]

element

def findmax(f,l):
	best_element_sofar = None
	best_f_value_sofar = None
	for i in range(len(l)-1):
		elt = l[i]
		f_value = f(elt)
		if best_f_value_sofar == None or \
			f_value > best_f_value_sofar:
			best_element_sofar = elt
			best_f_value_sofar = f_value
	return best_element_sofar

Modern programming languages like Python can understand hexadecimal
numbers natively! Try it:

print 0x234 # uncomment me to see 564 printed
print 0xb # uncomment me to see 11 printed

import ply.lex as lex

tokens = ('NUM', 'ID')

def test_lexer(input_string):
	lexer.input(input_string)
	result = [ ]
	while True:
		tok = lexer.token()
		if not tok: break
		result = result + [(tok.type,tok.value)]
	return result

specification

import re
re.findall(needle,haystack)

def t_LANGLESLASH(token):
    r'
def t_NUMBER(token):
	r"[0-9]+"
	token.value = int(token.value)
	return token
def t_STRING(token):
    r'"[^"]*"'
    return token
def t_WORD(token):
    r'[^ <>]+'
    return token
def t_IDENTIFIER(token):
    r'[a-zA-Z][a-zA-Z_]*'
    return token
def t_NUMBER(token):
    r'-?[0-9]+(:?\.[0-9]*)'   
    return token

simulator

edges = {(1,'a'):2,
	(2, 'a'): 2,
	(2, '1'): 3,
	(3, '1'): 3}
	accepting = [ 3 ]

	def fsmsim(string, current, edges, accepting):
		if string == ""
			return current in accepting
		else:
			letter = string[0]
			if (current, letter) in edges:
				destination = edges[(current,letter)]
				remaining_string = string[1:]
				return fsmsim(remaining_string,destination,edges,accepting)
			else:
				return False
	print fsmsim("aaa111",1,edges,accepting)
import re

def umnums(sentence):
	r = r"[0-9]+"
	sum = 0
	for found in re.findall(r,sentence):
		sum = sum + int(found)
	return sum
(?:[a-z]+-[a-z]+)|(?:[a-z]+)
def nfsmsim(string, current edges, accepting):
	if string == "":
		return current in accepting
	else:
		letter = string[0:1]
		if (current, letter) in edges:
			remainder = string[1:]
			newstates = edges[(current, letter)]
			for newstate in newstates:
				if nfsmsim(remainder, newstate, edges, accepting):
					return True
	if current in visited:
		return None
	elif current in accepting:
		return ""
	else:
		newvisited = visited + [current]
		for edge in edges:
			if edge[0] == curent:
				for newstate in edges[edge]:
					foo = nfsmaccepts(nestate, edges, accepting, newvisited)
					if foo != None:
						return edge[1] + foo
		return None

breaking points

Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> "Ada Lovelace".find(" ")
3
>>> "Alan Turing".find("n",4)
9
def myfirst_yoursecond(p,q):
	pindex = p.find(" ")
	qindex = q.find(" ")
	return p[ :pindex] == q[qindex+1:]
>>> "Python is fun".split()
['Python', 'is', 'fun']
>>> "July-August 1842".split()
['July-August', '1842']
>>> "6*9==42".split()
['6*9==42']

Regular expression [1-3][4-8][a-b]

>>> r"[0-9][0-9]"
>>> re.findall(r"[0-9][0-9]", "July 28, 1821")
>>> re.findall(r"[0-9][0-9]", "12345")

r”a+”, r”[0-1]+”
regular expression rule is maximum match eat single match
re.findall(r”[0-9][ ][0-9]+”, “a1 2b cc3 44d”)
r”[0-9]+%”
r”[a-z]+|[0-9]+”,”Goothe 1798″

regexp = r”[a-z]+-?[a-z]+”

>>> re.findall(r”[0-9].[0-9]”, “1a1 222 cc3”)
[‘1a1’, ‘222’]

edges = {(1,'a'):2,
	(2, 'a'): 2,
	(2, '1'): 3,
	(3, '1'): 3}

loop

public void beep()

public boolean checkAlarm()

public void alarm(){
	boolean on = checkAlarm();
	while(on){
		beep();
		on = checkAlarm();
	}

}
String googol = "1";
int len = googol.length();
while(len < 101){
	googol = googol + "0";
	len = googol.length();
}

while loop

public int keepRolling(){
	int dice1 = rollDice();
	int dice2 = rollDice();
	int count = 1;
	while(!(dice1 == dice2)){
		dice1 = rollDice();
		dice2 = rollDice();
		count = count + 1;
	}
	return count;
}
public void raiseAlarm(int numOfWarnings){
	int i = 1;
	while(i <= numOfWarnings){
		System.out.println("warning");
		i = i + 1;
	}
}
public void raiseAlarm(int numOfWarnings){
	for (int i = 1; i <= numOfWarnings; i++){
		System.out.println("Warning");
	}
}

pyramid

public int countBlocks(int levels){
	int sum = 0;
	for(int i = 1; i <= levels; i++)
	{
		sum = sum + i * i; 
	}
    return sum;
}
public int martingale(){
	int money = 1000;
	int target = 1200;
	int bet = 10;
	while(money>bet){
		boolean win = play();
		if(win){
			money += bet;
			bet = 10;
		}
		else {
			money -= bet;
			bet *= 2;
		}
	}
	return money;
}

Function

public void println(String x){
	if(x == null){
		x = "null";
	}
	try {
		ensureOpen();
		textOut.write(x);
	} catch(IOException e){
		trouble = true;
	}
	newLine();
}
boolean playButton; 

public void playMusic(){
    if (playButton){
        System.out.println("Music is playing");
    } else {
    	System.out.println("Music is paused");
    }
}

parameter and argument

public void greeting(String location){
	System.out.println("Hello, " + location);
}
public int likePhoto(int currentLikes, String comment, boolean like){
	System.out.println("Feedback: "+ comment);
	if(like){
		currentLikes = currentLikes + 1;
	}
	System.out.println("Number of likes: " + currentLikes);
	return currentLikes;
}
public double makeChange(double itemCost, double dollarsProvided){
	double change = dollarsProvided - itemCost;
	return change;
}

random number

double randomNumber = Math.random();
randomNumber = randomNumber * 10;
int randomInt = (int) randomNumber;
public int rollDice(){
	double randomNumber = Math.random();
	randomNumber = randomNumber * 6 + 1;
	int randomInt = (int) randomNumber;
	return randomInt;
}

java documentation
https://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html

Math.random()
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#random–