Zum Inhalt springen

Benutzer:Dirk Huenniger/python

Aus Wikibooks

Deprecated

[Bearbeiten]

This version of this document is deprecated. The source-codes use an old syntax of the Python programming language. It is very dangerous to learn this syntax, since the code you write using this syntax will not run on new installations anymore. A new version of this document is available here Benutzer:Dirk Huenniger/python3.0.


This is my little introduction to Python

But before getting started I just want to add a links to some files of a turtle graphics course in python which is also quite suitable for beginners. So HERE it is.



Hello World

[Bearbeiten]

Lets start with my slighly advanced version of the hello word program

print "Hello World"

#Functions
def funny_function(x):
	print "I am a function called with parameter ",x

funny_function("Horsefly")

#conditionals
if 1==2:
	print "One and Two are the same"
elif 1==1:
	print "One and One are the same"
else:
	print "One and One are different"

#the while loop
x=3
while x>1:
	print "While",x
	x-=1
	
#the for loop
for i in range(1,3):
	print "For",i

Objects

[Bearbeiten]

The next thing I would like to show you are the object oriented features of python.

#objects

class Animal:
	#constuctor
	def __init__(self):
		self.legs=0
		self.weight=0
		#private variable
		self.__answer=42
	def getLegs(self):
		return self.legs
	def setLegs(self,l):
		self.legs=l
	def getAnswer(self):
		return self.__answer
	
class Dog(Animal):
	def __init__(self):
		Animal.__init__(self)
		self.setLegs(4)
	def bark(self):
		print "Wow!"
	
d=Dog()
d.bark()
print d.getLegs()
print d.weight
print d.getAnswer()
print d.__answer

Strings

[Bearbeiten]

Of course there are a lot of functions dealing with strings in Python

#Printing a string
print "xyz"
#concatanating strings with the + operator
print "xyz"+"abc"
#multiplying a string
print 3*"xyz"
#getting the fifth character of a string
print "abcdefg"[4]
#printing the charactes 3 to 5 of a string
print "abcdefg"[2:5]
#printing the first 3 characters of a string
print "abcdefg"[:3]
#print the last chacters of a string starting from the fourth
print "abcdefg"[3:]
#print the second letter counting from the end of the sting
print "abcdefg"[-2]

A very important structure in Python is the list.

#putting together apples and pears
print ["apples","pears"]
#bascially you can to the same things with lists as with stings so
#multiply
print 3*["apples","pears"]
#add
print ["apples","pears"]+["spam","eggs"]
#take the third element
print ["apples","pears","spam","eggs"][2]
#and so on.
#of course you can also do normal stack , list and queue operations
l=["a","b","c"]
print l
#appending
l.append("d")
print l
#inserting
l.insert(2,"new")
print l
#stack poping, pop the element at the end
print l.pop()
print l
#queue poping, pop the element at the beginnig
print l.pop(0)
print l
#sorting
l.sort()
print l
#remove element by name
l.remove("new")
print l
#remove by index
l=[1,2,3,1,2,3]
print l
del l[2]
print l

Containers

[Bearbeiten]

But of course there are other useful container types too.

#the mapping type: dictionary, an associative array
d={"dirk":27,"arthur":24,"david":20,"linda":30}
print d
print d["dirk"]
print d.keys()
print d.values()
d.update({"dirk":28})
print d
d["david"]=21
print d
del d["arthur"]
print d
print d.has_key("linda")
print "dirk" in d
#the set type
l=[1,2,3,4,1,2]
print l
s=set(l)
print s
#"element of" realtionship
print 1 in s
print 5 in s
t=set([4,5])
#set difference
print s-t
#set union
print s|t
#set intersection
print s&t
#set symmetric difference
print s^t

Loops

[Bearbeiten]

Here come a short introduction to the way you loop through sequences in Python

d={"john":23,"anna":30,"elis":26}
for k , v in d.items():
	print "The key "+k+" has got the value "+str(v)

fruits=["apple","banana","orange"]
for i, f in enumerate(fruits):
	print "The fruit",f,"is number",i
	
drinks=["juice","water","lemonade"]
for f,d in zip(fruits,drinks):
	print d,f
	
for r in reversed(["a","b","c","d"]):
	print r

Exercise

[Bearbeiten]

Some Magic

[Bearbeiten]

The following lines are magic, just store them to the file mathparser.py

import parser
import pprint
from types import ListType, TupleType
import symbol
import token
import types
d=symbol.sym_name
d.update( token.tok_name)

def do(x):
	if type(x)==types.StringType:
		return x
	try:
		l=len(x)
	except:
		l=1
	if l>1:
		try:
			h=d[x[0]]
		except:
			h=x [0]
		if h in ["arith_expr"]:
			l=[h]
		else:
			l=[]
		for e in x[1:]:
			l+=[do(e)]
		return l
	else:
		return x
		
def press(x):
	if type(x)==types.StringType:
		return x
	if len(x)==1:
		try:
			return press(x[0])
		except:
			return x
	try:
		return [press(a) for a in x]		
	except:
		return x
	return x

def clean(x):
	if type(x)==types.StringType:
		return x
	try:
		return filter( lambda x : x not in ['arith_expr',"(",")",""] ,[clean(a) for a in x]  ) 		
	except:
		return x
	return x

def consume(x):
	if type(x)==types.StringType:
		return x
	if len(x)>2:
		return [consume(x[1]) , consume(x[0]) , consume(x[2:])]
	if len(x)==2:
		return [consume(x[0]),consume(x[1])]	
	return consume(x[0])


def parse(x):
	p=parser.expr(x).tolist()
	u=press(clean(press(do(p))))
	return press(clean(consume(u)))

Your Task

[Bearbeiten]

This is the desciption the task you can do

import mathparser
from types import ListType, TupleType
import types

print mathparser.parse("x*x*x")

#Task 1:
#Write a program that generates something like this:
#(x * (x * x))
#from the given source list

#HINT
#You can check whether something is a string by writing:
#if type(x)==types.StringType:
#an so on.

#Task 2:
#Write a program that calculates the first derivative of the given input list.
#The output format shall be a list of the same kind.


#Task 3:
# Combine 1 and 2 to get the derivative in the usual notation.

Solution

[Bearbeiten]

This is my solution to the problem

import mathparser
from types import ListType, TupleType
import types

def pri(x):
	if type(x)==types.StringType:
		return x
	if x[0] in "+-*/":
		return "(" + pri(x[1]) +" "+x[0]+" " + pri(x[2]) + ")"
	if len(x)==2:
		return x[0]+"("+pri(x[1])+")"

def mult(a,b):
	if ((b=="0") or (a=="0")):
		return "0"
	elif a=="1":
		return b
	elif b=="1":
		return a
	else:	
		return ["*" ,a,b]
		
def add(a,b):
	if a=="0":
		return b
	elif b=="0":
		return a
	else:
		return  ["+" ,a,b]

def derive(x):
	TODO="I will not calculate this derivative because the guy who programmed me didn't want me to"
	BADMATH="I will not calculate this derivative because, mathematicins can prove that it won't work all the time"
	if x=="x":
		return "1"
	if type(x)==types.StringType:
		return "0"
	if x[0] == "+":
		return add(derive(x[1]),derive(x[2]))
	elif x[0] == "-":
		return [x[0] ,derive(x[1]),derive(x[2])]
	elif x[0] in "*/":
		a=mult(derive(x[1]),x[2])		
		b=mult(x[1],derive(x[2]))
		if x[0]=="*":
			return add(a,b)
		else:
			return ["-" ,a,b]
	elif x[0]=="sin":
		return mult(["cos" ,x[1] ] , derive(x[1])) 
	elif x[0]=="cos":
		return mult(mult("-1",["sin" ,x[1]]) , derive(x[1])) 
	elif x[0]=="log":
		return mult(["/","1","x" ] , derive(x[1])) 
	elif x[0] in ["ln","ceil","fabs","floor","fmod","frexp"]:
		raise BADMATH
	elif x[0] in ["modf","ldexp"]:
		raise TODO
	elif x[0]=="exp":
		return mult(["exp",x[1] ] , derive(x[1])) 
	elif x[0]=="log":
		if len(x)==2:
			return mult(["exp",x[1] ] , derive(x[1])) 
		else:
			raise TODO
	elif x[0]=="log10":
		return derive(["log",x[1],"10.0"])
	elif x[0]=="pow":
		if not contains_x(x[2]):
			return ["pow", x ]
		else:
			raise TODO

print pri(mathparser.parse("x*x*x"))
print derive(mathparser.parse("x*x*x"))
print pri(derive(mathparser.parse("x*x*x")))