From 61458c8ff39bf34b83761dc7a2537e4618f1841d Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 13 Sep 2012 00:22:06 +0800 Subject: [PATCH 1/2] first commit --- binarysearch.py | 25 ++++++++++++++++ btree.py | 62 +++++++++++++++++++++++++++++++++++++++ graph.py | 35 ++++++++++++++++++++++ queue.py | 43 +++++++++++++++++++++++++++ sort.py | 78 +++++++++++++++++++++++++++++++++++++++++++++++++ stack.py | 59 +++++++++++++++++++++++++++++++++++++ 6 files changed, 302 insertions(+) create mode 100644 binarysearch.py create mode 100644 btree.py create mode 100644 graph.py create mode 100644 queue.py create mode 100644 sort.py create mode 100644 stack.py diff --git a/binarysearch.py b/binarysearch.py new file mode 100644 index 0000000..fa6a1e2 --- /dev/null +++ b/binarysearch.py @@ -0,0 +1,25 @@ +def BinarySearch(l,key): + low=0 + high=len(l)-1 + i=0 + while(low <= high): + i = i+1 + mid = low + ((high-low)>>1) + if(l[mid] < key): + low = mid + 1 + elif (l[mid] > key): + high = mid -1 + else: + print "use %d times" % i + return mid + return -1 + +if __name__ == "__main__": + l=[1,4,5,6,7,8,9,44,333,2233] + print l + print BinarySearch(l,4) + print BinarySearch(l,44) + print BinarySearch(l,8) + print BinarySearch(l,2233) + print BinarySearch(l,77) + diff --git a/btree.py b/btree.py new file mode 100644 index 0000000..69434e8 --- /dev/null +++ b/btree.py @@ -0,0 +1,62 @@ +class BTree: + def __init__(self,value): + self.left=None + self.data=value + self.right=None + + def insertLeft(self,value): + self.left=BTree(value) + return self.left + + def insertRight(self,value): + self.right=BTree(value) + return self.right + + def show(self): + print self.data + +def preorder(node): + if node.data: + node.show() + if node.left: + preorder(node.left) + if node.right: + preorder(node.right) + +def inorder(node): + if node.data: + if node.left: + inorder(node.left) + node.show() + if node.right: + inorder(node.right) + +def postorder(node): + if node.data: + if node.left: + postorder(node.left) + if node.right: + postorder(node.right) + node.show() + +if __name__ == "__main__": + + Root=BTree("root") + A=Root.insertLeft("A") + C=A.insertLeft("C") + D=C.insertRight("D") + F=D.insertLeft("F") + G=D.insertRight("G") + B=Root.insertRight("B") + E=B.insertRight("E") + + print "pre-traversal" + preorder(Root) + + print "in-traversal" + inorder(Root) + + print "post-traversal" + postorder(Root) + + diff --git a/graph.py b/graph.py new file mode 100644 index 0000000..834670b --- /dev/null +++ b/graph.py @@ -0,0 +1,35 @@ +def searchGraph(graph,start,end): + results=[] + generatePath(graph,[start],end,results) + results.sort(lambda x,y:cmp(len(x),len(y))) + return results + +def generatePath(graph,path,end,results): + state=path[-1] + if state == end: + results.append(path) + else: + for arc in graph[state]: + if arc not in path: + generatePath(graph,path+[arc],end,results) + + +if __name__ == "__main__": + Graph={ + 'A':['B','C','D'], + 'B':['E'], + 'C':['D','F'], + 'D':['B','E','G'], + 'E':[], + 'F':['D','G'], + 'G':['E'] + } + r = searchGraph(Graph,'A','D') + print "A to D" + for i in r: + print i + + r=searchGraph(Graph,'A','E') + print "A to E" + for i in r: + print i diff --git a/queue.py b/queue.py new file mode 100644 index 0000000..64da3e4 --- /dev/null +++ b/queue.py @@ -0,0 +1,43 @@ +class Queue: + def __init__(self,size=20): + self.queue=[] + self.size=size + self.end=-1 + + def setSize(self,size): + self.size=size + + def In(self,element): + if self.end < self.size -1: + self.queue.append(element) + self.end = self.end + 1 + else: + raise "QueueFull" + + def Out(self): + if self.end != -1: + element = self.queue[0] + self.queue=self.queue[1:] + self.end = self.end-1 + return element + else: + raise "QueueEmpty" + + def End(self): + return self.end + + def empty(self): + self.queue=[] + self.end=-1 + +if __name__ == "__main__": + + queue=Queue() + for i in range(10): + queue.In(i) + print queue.End() + + for i in range(10): + print queue.Out() + + diff --git a/sort.py b/sort.py new file mode 100644 index 0000000..b190701 --- /dev/null +++ b/sort.py @@ -0,0 +1,78 @@ +class BTree: + def __init__(self,value): + self.left=None + self.data=value + self.right=None + + def insertLeft(self,value): + self.left=BTree(value) + return self.left + + def insertRight(self,value): + self.right=BTree(value) + return self.right + + def show(self): + print self.data + +def inorder(node): + if node.data: + if node.left: + inorder(node.left) + node.show() + if node.right: + inorder(node.right) + + +def rinorder(node): + if node.data: + if node.right: + rinorder(node.right) + node.show() + if node.left: + rinorder(node.left) + +def insert(node,value): + if value > node.data: + if node.right: + insert(node.right,value) + else: + node.insertRight(value) + else: + if node.left: + insert(node.left,value) + else: + node.insertLeft(value) + + +if __name__ == "__main__": + + l=[88,11,2,33,22,4,55,33,221,34] + Root=BTree(l[0]) + node=Root + for i in range(1,len(l)): + insert(Root,l[i]) + + print "1---->10" + inorder(Root) + print "10--->1" + rinorder(Root) + + + + + + + + + + + + + + + + + + + diff --git a/stack.py b/stack.py new file mode 100644 index 0000000..e5b65ce --- /dev/null +++ b/stack.py @@ -0,0 +1,59 @@ +class Stack: + def __init__(self,size=20): + self.stack= [] + self.size= size; + self.top= -1 + + def setSize(self,size): + self.size=size; + + def push(self,element): + if self.isFull(): + raise "StackOverflow" + else: + self.stack.append(element) + self.top = self.top + 1 + + def pop(self): + if self.isEmpty(): + raise "StackUnderflow" + else: + element=self.stack[-1] + self.top=self.top-1; + del self.stack[-1] + return element + + def Top(self): + return self.top + + def empty(self): + self.stack=[] + self.top=-1 + + def isEmpty(self): + if self.top == -1: + return True + else: + return False + + def isFull(self): + if self.top == self.size-1: + return True + else: + return False + +if __name__ == "__main__": + + stack=Stack() + + for i in range(10): + stack.push(i) + print stack.Top() + + for i in range(10): + print stack.pop() + + stack.empty() + print stack.Top() + + From 9a70fe0e3e35b026692c720dd9127661ea7c1df5 Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 13 Sep 2012 01:01:41 +0800 Subject: [PATCH 2/2] Signed-off-by: Jimmy --- base/10/card.py | 33 +++++++++++ base/10/carddata.txt | 1 + base/10/cardlog.txt | 2 + base/10/myexc.py | 104 ++++++++++++++++++++++++++++++++ base/11/Gui.py | 17 ++++++ base/11/deco.py | 22 +++++++ base/11/easyMath.py | 40 +++++++++++++ base/11/grabWeb.py | 26 ++++++++ base/11/numconv.py | 8 +++ base/11/odd.py | 10 ++++ base/11/testit.py | 26 ++++++++ base/12/hot.py | 10 ++++ base/13/NumStr.py | 27 +++++++++ base/13/Rand.py | 10 ++++ base/13/file.py | 34 +++++++++++ base/13/meta.py | 28 +++++++++ base/13/roundFloat.py | 9 +++ base/13/time.py | 28 +++++++++ base/13/time60.py | 14 +++++ base/16/sockCli.py | 20 +++++++ base/16/sockServ.py | 17 ++++++ base/16/tcpclient.py | 21 +++++++ base/16/tcpserver.py | 26 ++++++++ base/16/udpCli.py | 19 ++++++ base/16/udpSer.py | 17 ++++++ base/18/sleep.py | 26 ++++++++ base/18/threading.py | 37 ++++++++++++ base/19/label.py | 11 ++++ base/2/2_10.py | 10 ++++ base/2/2_11.py | 25 ++++++++ base/2/2_2.py | 9 +++ base/2/2_7.py | 5 ++ base/2/2_8.py | 7 +++ base/20/Cralwer.py | 114 ++++++++++++++++++++++++++++++++++++ base/3/makeFile.py | 14 +++++ base/3/makeTextFile.py | 32 ++++++++++ base/3/readTextFile.py | 17 ++++++ base/4/display.py | 11 ++++ base/6/idcheck.py | 20 +++++++ base/6/queue.py | 38 ++++++++++++ base/6/stack.py | 43 ++++++++++++++ base/6/unicode.txt | 1 + base/6/unicodeFile.py | 20 +++++++ base/7/userpw.py | 53 +++++++++++++++++ base/9/ospathex.py | 38 ++++++++++++ data_struct/binarysearch.py | 25 ++++++++ data_struct/btree.py | 62 ++++++++++++++++++++ data_struct/graph.py | 35 +++++++++++ data_struct/queue.py | 43 ++++++++++++++ data_struct/sort.py | 78 ++++++++++++++++++++++++ data_struct/stack.py | 59 +++++++++++++++++++ 51 files changed, 1402 insertions(+) create mode 100644 base/10/card.py create mode 100644 base/10/carddata.txt create mode 100644 base/10/cardlog.txt create mode 100644 base/10/myexc.py create mode 100644 base/11/Gui.py create mode 100644 base/11/deco.py create mode 100644 base/11/easyMath.py create mode 100644 base/11/grabWeb.py create mode 100644 base/11/numconv.py create mode 100644 base/11/odd.py create mode 100644 base/11/testit.py create mode 100644 base/12/hot.py create mode 100644 base/13/NumStr.py create mode 100644 base/13/Rand.py create mode 100644 base/13/file.py create mode 100644 base/13/meta.py create mode 100644 base/13/roundFloat.py create mode 100644 base/13/time.py create mode 100644 base/13/time60.py create mode 100644 base/16/sockCli.py create mode 100644 base/16/sockServ.py create mode 100644 base/16/tcpclient.py create mode 100644 base/16/tcpserver.py create mode 100644 base/16/udpCli.py create mode 100644 base/16/udpSer.py create mode 100644 base/18/sleep.py create mode 100644 base/18/threading.py create mode 100644 base/19/label.py create mode 100644 base/2/2_10.py create mode 100644 base/2/2_11.py create mode 100644 base/2/2_2.py create mode 100644 base/2/2_7.py create mode 100644 base/2/2_8.py create mode 100644 base/20/Cralwer.py create mode 100644 base/3/makeFile.py create mode 100644 base/3/makeTextFile.py create mode 100644 base/3/readTextFile.py create mode 100644 base/4/display.py create mode 100644 base/6/idcheck.py create mode 100644 base/6/queue.py create mode 100644 base/6/stack.py create mode 100644 base/6/unicode.txt create mode 100644 base/6/unicodeFile.py create mode 100644 base/7/userpw.py create mode 100644 base/9/ospathex.py create mode 100644 data_struct/binarysearch.py create mode 100644 data_struct/btree.py create mode 100644 data_struct/graph.py create mode 100644 data_struct/queue.py create mode 100644 data_struct/sort.py create mode 100644 data_struct/stack.py diff --git a/base/10/card.py b/base/10/card.py new file mode 100644 index 0000000..e6bac33 --- /dev/null +++ b/base/10/card.py @@ -0,0 +1,33 @@ +def safe_float(obj): + try: + retval = float(obj) + except (ValueError,TypeError),diag: + retval = str(diag) + return retval + +def main(): + log = open("cardlog.txt","w") + try: + ccfile = open("carddata.txt","r") + except IOError,e: + log.write("no txns this \n") + log.close() + return + txns = ccfile.readlines() + ccfile.close() + total = 0.00 + log.write("account log:\n") + + for eachTxn in txns: + result = safe_float(eachTxn) + if isinstance(result,float): + total += result + log.write("data ....processed\n") + else: + log.write("ignored: %s" % result) + print "$%.2f (new balance)" % (total) + log.close() + +if __name__ == '__main__': + print "run" + main() diff --git a/base/10/carddata.txt b/base/10/carddata.txt new file mode 100644 index 0000000..bd41cba --- /dev/null +++ b/base/10/carddata.txt @@ -0,0 +1 @@ +12345 \ No newline at end of file diff --git a/base/10/cardlog.txt b/base/10/cardlog.txt new file mode 100644 index 0000000..c97b068 --- /dev/null +++ b/base/10/cardlog.txt @@ -0,0 +1,2 @@ +account log: +data ....processed diff --git a/base/10/myexc.py b/base/10/myexc.py new file mode 100644 index 0000000..0e3245f --- /dev/null +++ b/base/10/myexc.py @@ -0,0 +1,104 @@ + +import os,socket,errno,types,tempfile + +class NetworkError(IOError): + pass + +class FileError(IOError): + pass + +def updArgs(args,newarg=None): + if isinstance(args,IOError): + myargs =[] + myargs.extend([arg for arg in args]) + else: + myargs = list(args) + + if newarg: + myargs.append(newarg) + + return tuple(myargs) + +def fileAargs(file,mode,agrs): + if args[0] == errno.EACCES and \ + 'access' in dir(os): + perms = '' + perms = {'r':os.R_OK,'w':os.W_OK,'x':os.X_OK} + pkeys = permd.keys() + pkeys.sort() + pkeys.reverse() + + for eachPerm in 'rwx': + if os.access(file,permd[eachPerm]): + perms += eachPerm + else: + perms += '-' + + if isinstance(args,IOError): + myargs = [] + myargs.extend([arg for arg in args]) + else: + myargs = list(args) + + myargs[1] = "'%s' %s (perms:'%s')" % (mode,myargs[1],perms) + + myargs.append(args.filename) + + else: + myargs = args + return tuple(myargs) + +def myconnnect(sock,host,port): + try: + sock.connect((hosy,port)) + except socket.error,args: + myargs = updArgs(args) + if len(myargs) == 1: + myargs = (errno.ENXIO,myargs[0]) + + raise NetworkError,\ + updArgs(myargs,host +":" + str(port)) +def myopen(file,mode ="r"): + try: + fo = open(file,mode) + except IOError,args: + raise FileError,fileArgs(file,mode,args) + return fo + +def testfile(): + file = mkdtemp() + f = open(file,"w") + f.close() + + for eachTest in ((0,"r"),(0100,"r"), \ + (0400,"w"),(0500,"w")): + try: + os.chmod(file,eachTest[0]) + f=myopen(file,eachTest[1]) + + except FileError,args: + print "%s: %s" % \ + (args.__class__.__name__,args) + else: + print file,"open ok..perm ignored" + f.close() + os.chmod(file,0777) + os.unlink(file) +def testnet(): + s = socket.socket(socket.AF_INET.socket.SOCK_STREAM) + for eachHost in ("deli","www"): + try: + myconnect(s,"deli",8080) + except NetworkError,args: + print "%s:%s" %\ + (args.__class__.__name__,args) +if __name__ == "__main__": + testfile() + testnet() + + + + + + + diff --git a/base/11/Gui.py b/base/11/Gui.py new file mode 100644 index 0000000..6bff1f6 --- /dev/null +++ b/base/11/Gui.py @@ -0,0 +1,17 @@ + +from functools import partial +import Tkinter + +root=Tkinter.Tk() +MyButton = partial(Tkinter.Button,root, + fg="white",bg="blue") +b1= MyButton(text="button 1") +b2=MyButton(text="button 2") +#qb=MyButton(text="QUIT",bg="red", + # command=root.quit) + +b1.pack() +b2.pack() +#qb.pack(file=Tkinter.X,expand= True) +root.title("PFAs!") +root.mainloop() diff --git a/base/11/deco.py b/base/11/deco.py new file mode 100644 index 0000000..21d7389 --- /dev/null +++ b/base/11/deco.py @@ -0,0 +1,22 @@ + +from time import ctime,sleep + +def tsfunc(func): + def wrappedFunc(): + print "[%s] %s() called" % \ + (ctime(),func.__name__) + return func() + return wrappendFunc + +@tsfunc +def foo(): + pass + +foo() +sleep(4) + +for i in range(2): + sleep(1) + foo() + + diff --git a/base/11/easyMath.py b/base/11/easyMath.py new file mode 100644 index 0000000..e14d53b --- /dev/null +++ b/base/11/easyMath.py @@ -0,0 +1,40 @@ + +from operator import add,sub +from random import randint,choice + +ops ={"+":add,"-":sub} +MAXTRIES = 2 + +def doprob(): + op = choice('+-') + nums = [randint(1,10) for i in range(2)] + nums.sort(reverse = True) + ans = ops[op](*nums) + pr="%d %s %d =" %(nums[0],op,nums[1]) + oops =0 + while True: + try: + if int(raw_input(pr)) == ans: + print "corrent" + break + if oops == MAXTRIES: + print "answer \n %s%d" %(pr,ans) + else: + print "incorrent...try again" + oops += 1 + except (KeyboardInterrupt, EOFError,ValueError): + print "invalid input ... try again" + +def main(): + while True: + doprob() + try: + opt= raw_input("Again?[y]".lower()) + if opt and opt[0] == "n": + break + except (KeyboardInterrupt,EOFError): + break +if __name__ == "__main__": + main() + + diff --git a/base/11/grabWeb.py b/base/11/grabWeb.py new file mode 100644 index 0000000..5b3de06 --- /dev/null +++ b/base/11/grabWeb.py @@ -0,0 +1,26 @@ + +from urllib import urlretrieve + +def firstNoBlank(lines): + for eachLine in lines: + if not eachLine.strip(): + continue + else: + return eachLine + +def firstLast(webpage): + f = open(webpage) + lines= f.readlines() + f.close() + print firstNoBlank(lines),lines.reverse() + print firstNoBlank(lines), + +def download(url = "http://www.cqupt.edu.cn",process=firstLast): + try: + retval = urlretrieve(url)[0] + except IOError: + retval = None + if retval: + process(retval) +if __name__ == "__main__": + download() diff --git a/base/11/numconv.py b/base/11/numconv.py new file mode 100644 index 0000000..63eb282 --- /dev/null +++ b/base/11/numconv.py @@ -0,0 +1,8 @@ + +def convert(func,seq): + return[func (eachNum ) for eachNum in seq] + +myseq=(123,45.67,-6.2e8,99999999L) +print convert(int,myseq) +print convert(long,myseq) +print convert(float,myseq) diff --git a/base/11/odd.py b/base/11/odd.py new file mode 100644 index 0000000..2a37d6a --- /dev/null +++ b/base/11/odd.py @@ -0,0 +1,10 @@ + +from random import randint + +#def odd(n): +# return n%2 + +allNums =[] +for eachNum in range(9): + allNums.append(randint(1,99)) +print[n for n in allNums if n%2] diff --git a/base/11/testit.py b/base/11/testit.py new file mode 100644 index 0000000..ad5037e --- /dev/null +++ b/base/11/testit.py @@ -0,0 +1,26 @@ + +def testit(func,*nkwargs,**kwargs): + try: + retval = func(*nkwargs,**kwargs) + result = (True,retval) + except Exception,diag: + result = (False,str(diag)) + return result + +def test(): + funcs =(int,long,float) + vals = (1234,12.34,"1234","12.34") + + for eachFunc in funcs: + print "_"*20 + for eachVal in vals: + retval = testit(eachFunc,eachVal) + if retval[0]: + print "%s(%s)=" % \ + (eachFunc.__name__,"eachVal"),retval[1] + else: + print "%s(%s)=FAILED:" %\ + (eachFunc.__name__,"eachVal"),retval[1] + +if __name__ == "__main__": + test() diff --git a/base/12/hot.py b/base/12/hot.py new file mode 100644 index 0000000..e695791 --- /dev/null +++ b/base/12/hot.py @@ -0,0 +1,10 @@ +class HotelRoomCalc(object): + 'hotel room rate calculator' + def __init__(self,rt,sales=0.085,rm=0.1): + self.salesTax = sales + self.roomTax = rm + self.roomRate = rt + + def calcTotal(self,days = 1): + daily = round((self.roomRate *(1+self.roomTax + self.salesTax)),2) + return float(days)*daily diff --git a/base/13/NumStr.py b/base/13/NumStr.py new file mode 100644 index 0000000..986062b --- /dev/null +++ b/base/13/NumStr.py @@ -0,0 +1,27 @@ +class NumStr(object): + def __init__(self,num=0,string=''): + self.__num = num + self.__string = string + + def __str__(self): + return "[%d :: %r]" % (self.__num,self.__string) + __repr__ = __str__ + + def __add__(self,other): + if isinstance(other,NumStr): + return self.__class__(self.__num + \ + other.__num,self.__string+other.__string) + else: + return TypeError,"type error" + def __mul__(self,num): + if isinstance(num,int): + return self.__class__(self.__num *num,self.__string *num) + else: + raise TypeError,"__num__ error" + def __nonzero__(self): + return self.__num or len(self.__string) + def __norm_cval(self,cmpres): + return cmp(cmpres,0) + def __cmp__(self,other): + return self.__norm_cval(cmp(self.__num,other.__num)) + \ + self.__norm_cval(cmp(self.__string,other.__string)) diff --git a/base/13/Rand.py b/base/13/Rand.py new file mode 100644 index 0000000..1b56d0d --- /dev/null +++ b/base/13/Rand.py @@ -0,0 +1,10 @@ + +from random import choice + +class Rand(object): + def _init_(self,seq): + self.data = seq + def _iter_(self): + return self + def next(self): + return choice(self.data) diff --git a/base/13/file.py b/base/13/file.py new file mode 100644 index 0000000..8830909 --- /dev/null +++ b/base/13/file.py @@ -0,0 +1,34 @@ +import os +import pickle + +class File(object): + saved=[] + def __init__(self,name=None): + self.name = name + def __get__(self,obj,typ=None): + if self.name not in File.saved: + raise AttributeError,"%r used before assignment " % self.name + try: + f = open(self.name,"r") + val = pickle.load(f) + f.close() + return val + except (pickle.UnpicklingError,IOError,EOFError,AttributeError,\ + ImportError,IndexError),e: + raise AttributeError,"could not read %r:%s" % (self.name,e) + def __set__(self,obj,val): + f = open(self.name,"w") + try: + pickle.dump(val,f) + File.saved.append(self.name) + except (TypeError,pickle.PicklingError),e: + raise AttributeError,"could not pickle %r " % self.name + finally: + f.close() + + def __delete__(self,obj): + try: + os.unlink(self.name) + File.saved.remove(self.name) + except (OSError,ValueError),e: + pass diff --git a/base/13/meta.py b/base/13/meta.py new file mode 100644 index 0000000..243a253 --- /dev/null +++ b/base/13/meta.py @@ -0,0 +1,28 @@ +from warnings import warn + +class ReqStr(type): + def __init__(cls,name,bases,attrd): + super(ReqStr,cls).__init__(name,bases,attrd) + if "__str__" not in attrd: + raise TypeError("class overring __str__") + if "__repr__" not in attrd: + warn("class suggests __repr__",stacklevel = 3) +print "define ReqStr (meta)class \n" + +class Foo(object): + __metaclass__ = ReqStr + + def __str__(self): + return "instance of class",self.__class__.__name__ +print "defined Foo class\n" + +class Bar(object): + __metaclass__ = ReqStr + + def __str__(self): + return self.__class__.__name__ +print "defined Bar class\n " + +class FooBar(object): + __metaclass__ = ReqStr +print "defined FooBar class \n" diff --git a/base/13/roundFloat.py b/base/13/roundFloat.py new file mode 100644 index 0000000..06cf9bf --- /dev/null +++ b/base/13/roundFloat.py @@ -0,0 +1,9 @@ +class RoundFloat(object): + def __init__(self,val): + assert isinstance(val,float),"Value must be a float" + self.value = round(val,2) + + def __str__(self): + return "%.2f" %self.value + __repr__ = __str__ + diff --git a/base/13/time.py b/base/13/time.py new file mode 100644 index 0000000..de514b5 --- /dev/null +++ b/base/13/time.py @@ -0,0 +1,28 @@ + +from time import time,ctime + +class Time(object): + def __init__(self,obj): + self.__data = obj; + self.__ctime = self.__mtime =self.__atime=time() + def get(self): + self.__atime = time() + return self.__data + def gettimeval(self,t_type): + if not isinstance(t_type,str) or t_type[0] not in "cma": + raise TypeError," arg c m a" + return getattr(self,"_%s__%stime" % (self.__class__.__name__,t_type[0])) + def gettimestr(self,t_type): + return ctime(self.gettimeval(t_type)) + def set(self,obj): + self.__data = obj; + self.__mtime = self.__atime= time() + def __repr__(self): + self.__atime = time() + return 'self.__data' + def __str__(self): + self.__atime = time() + return str(self.__data) + def __getatt__(self,attr): + self.__atime = time() + return getattr(self.__data,attr) diff --git a/base/13/time60.py b/base/13/time60.py new file mode 100644 index 0000000..a61ca1e --- /dev/null +++ b/base/13/time60.py @@ -0,0 +1,14 @@ +class Time60(object): + def __init__(self,hr,min): + self.hr = hr + self.min = min + def __str__(self): + return "%d:%d" %(self.hr,self.min) + __repr__ = __str__ + + def __add__(self,other): + return self.__class__(self.hr + other.hr,self.min+other.min) + def __iadd__(self,other): + self.hr += other.hr + self.min += other.min + return self diff --git a/base/16/sockCli.py b/base/16/sockCli.py new file mode 100644 index 0000000..f97acee --- /dev/null +++ b/base/16/sockCli.py @@ -0,0 +1,20 @@ +from socket import * + +HOST ="localhost" +PORT = 8888 +BUFSIZ = 1024 +ADDR = (HOST,PORT) + +while True: + tcpCliSock = socket(AF_INET,SOCK_STREAM) + tcpCliSock.connect(ADDR) + data=raw_input(">") + + if not data: + break + tcpCliSock.send("%s\r\n" % data) + data = tcpCliSock.recv(BUFSIZ) + if not data: + break + print data.strip() + tcpCliSock.close() diff --git a/base/16/sockServ.py b/base/16/sockServ.py new file mode 100644 index 0000000..9e4e38f --- /dev/null +++ b/base/16/sockServ.py @@ -0,0 +1,17 @@ +from SocketServer import (TCPServer as TCP, + StreamRequestHandler as SRH) +from time import ctime + +HOST='' +PORT=8888 +ADDR=(HOST,PORT) + +class MyRequestHandler(SRH): + def handle(self): + print "......connected from :",self.client_address + self.wfile.write('[%s] %s' % + (ctime(),self.rfile.readline())) + +tcpSer = TCP(ADDR,MyRequestHandler) +print "waiting for connection..." +tcpSer.serve_forever() diff --git a/base/16/tcpclient.py b/base/16/tcpclient.py new file mode 100644 index 0000000..b346fc6 --- /dev/null +++ b/base/16/tcpclient.py @@ -0,0 +1,21 @@ +from socket import * + +HOST = "localhost" +PORT = 21567 +BUFSIZ = 1024 +ADDR=(HOST,PORT) + +tcpCliSock = socket(AF_INET,SOCK_STREAM) +tcpCliSock.connect(ADDR) + +while True: + data = raw_input(">") + if not data: + break + tcpCliSock.send(data) + data = tcpCliSock.recv(BUFSIZ) + if not data: + break + print data + +tcpCliSock.close() diff --git a/base/16/tcpserver.py b/base/16/tcpserver.py new file mode 100644 index 0000000..688b0aa --- /dev/null +++ b/base/16/tcpserver.py @@ -0,0 +1,26 @@ + +from socket import * +from time import ctime + +HOST ='' +PORT=21567 +BUFSIZ = 1024 +ADDR =(HOST,PORT) + +tcpSerSock = socket(AF_INET,SOCK_STREAM) +tcpSerSock.bind(ADDR) +tcpSerSock.listen(5) + +while True: + print "waiting from connection..." + tcpCliSock,addr = tcpSerSock.accept() + print "...connected from :",addr + + while True: + data = tcpCliSock.recv(BUFSIZ) + if not data: + break + tcpCliSock.send('[%s] %s' %(ctime(),data)) + + tcpCliSock.close() +tcpSerSock.close() diff --git a/base/16/udpCli.py b/base/16/udpCli.py new file mode 100644 index 0000000..9a502f3 --- /dev/null +++ b/base/16/udpCli.py @@ -0,0 +1,19 @@ +from socket import * + +HOST="localhost" +PORT=21567 +BUFSIZ = 1024 +ADDR= (HOST,PORT) + +udpCliSock= socket(AF_INET,SOCK_DGRAM) + +while True: + data = raw_input(">") + if not data: + break + udpCliSock.sendto(data,ADDR) + data,ADDR= udpCliSock.recvfrom(BUFSIZ) + if not data: + break + print data +udpCliSock.close() diff --git a/base/16/udpSer.py b/base/16/udpSer.py new file mode 100644 index 0000000..bf7eabb --- /dev/null +++ b/base/16/udpSer.py @@ -0,0 +1,17 @@ +from socket import * +from time import ctime + +HOST ='' +PORT=21567 +BUFSIZ=1024 +ADDR =(HOST,PORT) + +udpSerSock = socket(AF_INET,SOCK_DGRAM) +udpSerSock.bind(ADDR) + +while True: + print "waiting for message..." + data,addr = udpSerSock.recvfrom(BUFSIZ) + udpSerSock.sendto('[%s] %s' %(ctime(),data),addr) + print "...received from and returned to :",addr +udpSerSock.close() diff --git a/base/18/sleep.py b/base/18/sleep.py new file mode 100644 index 0000000..65c80cd --- /dev/null +++ b/base/18/sleep.py @@ -0,0 +1,26 @@ +from time import sleep,ctime +import thread + +loops =[4,2,11] +def loop(nloop,nsec,lock): + print " start loop:",nloop,"at",ctime() + sleep(nsec) + print "loop :",nloop, "done at:",ctime() + +def main(): + print "start at:", ctime() + locks = [] + nloops = range(len(loops)) + + for i in nloops: + lock = thread.allocate_lock() + lock.acquire() + locks.append(lock) + for i in nloops: + thread.start_new_thread(loop,(i,loops[i],locks[i])) + for i in nloops: + while locks[i].locked():pass + + print " all done at:" ,ctime() +if __name__ == "__main__": + main() diff --git a/base/18/threading.py b/base/18/threading.py new file mode 100644 index 0000000..367fcf3 --- /dev/null +++ b/base/18/threading.py @@ -0,0 +1,37 @@ +import threading +from time import sleep,ctime + +loops = [4,2] + +class ThreadFunc(object): + def __init__(self,func,args,name=""): + self.name = name + self.name = func + self.args = args + def __call__(self): + apply(self.func,slef.args) + + def loop(nloop,nsec): + print "start loop:",nloop,"at:",ctime() + sleep(nsec) + print "loop",nloop,"done at:",ctime() + + def main(): + print "starting at:",ctime() + threads = [] + nloops = range(len(loops)) + #创建线程 + for i in nloops: + t = threading.Thread(target = loop,args=(i,loops[i])) + threads.append(t); + #启动线程 + for i in nloops: + threads[i].start() + #等待线程 + for i in nloops: + threads[i].join() + print "all DONE at:",ctime() + +if __name__ == "__main__": + main() + diff --git a/base/19/label.py b/base/19/label.py new file mode 100644 index 0000000..cec761f --- /dev/null +++ b/base/19/label.py @@ -0,0 +1,11 @@ +import Tkinter + +top = Tkinter.Tk() + +label = Tkinter.Label(top,text="input") +label.pack() + +button = Tkinter.Button(top,text="QIUT",command=top.quit,bg="red",fg="white") +button.pack(fill=Tkinter.X,expand=1) + +Tkinter.mainloop() diff --git a/base/2/2_10.py b/base/2/2_10.py new file mode 100644 index 0000000..d2dec79 --- /dev/null +++ b/base/2/2_10.py @@ -0,0 +1,10 @@ +a = 19 +print "please input a int number in 1-100" +x = raw_input() +while x != a: + print "sorry error: \n input again:" + x = raw_input() +if x == a: + print "you are right" + break +raw_input() diff --git a/base/2/2_11.py b/base/2/2_11.py new file mode 100644 index 0000000..5c3877d --- /dev/null +++ b/base/2/2_11.py @@ -0,0 +1,25 @@ +print "Menu: input the choice\n" +print "s: sum" +print "a: avg" +print "x: exit" +aa =[1,2,3,4] +while True: + ch = raw_input() + if ch == 's': + i = 0 + Sum = 0 + print "you choice sum:\n" + for i in aa: + Sum += i + print Sum + if ch == 'a': + print "you choice avg:\n" + i = 0 + Sum1 = 0 + for i in aa: + Sum1 += i + avg = float(Sum1)/(len(aa)) + print avg + if ch == 'x': + break + diff --git a/base/2/2_2.py b/base/2/2_2.py new file mode 100644 index 0000000..5d71d06 --- /dev/null +++ b/base/2/2_2.py @@ -0,0 +1,9 @@ +a = '19' +print "please input a int number in 1-100" +x = raw_input() +if a != x: + print "sorry you are wrong!\ninput again:" + x = raw_input() +else + print "you are right" +raw_input() diff --git a/base/2/2_7.py b/base/2/2_7.py new file mode 100644 index 0000000..8405c4b --- /dev/null +++ b/base/2/2_7.py @@ -0,0 +1,5 @@ +s = raw_input() +i = 0 +for i in s: + print i +raw_input() diff --git a/base/2/2_8.py b/base/2/2_8.py new file mode 100644 index 0000000..7ea33df --- /dev/null +++ b/base/2/2_8.py @@ -0,0 +1,7 @@ +s=[1,2,3,4,5,6] +i = 0 +t = 0 +for i in s: + t += i +print float(t)/len(s) +raw_input() diff --git a/base/20/Cralwer.py b/base/20/Cralwer.py new file mode 100644 index 0000000..3afa5d2 --- /dev/null +++ b/base/20/Cralwer.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python + +from sys import argv +from os import makedirs,unlink,sep +from os.path import dirname,exists,isdir,splitext +from string import replace,find,lower +from htmllib import HTMLParser +from urllib import urlretrieve +from urlparse import urlparse,urljoin +from formatter import DumbWriter,AbstractFormatter +from cStringIO import StringIO + +class Retriever(object):#下载网页类 + + def __init__(self,url): + self.url = url + self.file = self.filename(url) + + def filename(self,url,deffile ="index.htm"): + parsedurl = urlparse(url,"http:",0) #解析路径 + path = parsedurl[1] + parsedurl[2] + ext = splitext(path) + if ext[1] == "": #如果没有文件,使用默认 + if path[-1] == "/": + path += deffile + else: + path += "/" + deffile + ldir = dirname(path) #本地目录 + if sep != "/": + ldir = replace(ldir,"/",sep) + if not isdir(ldir): #如果没有目录,创建一个 + if exists(ldir):unlink(ldir) + makedirs(ldir) + return path + + def download(self):# 下载网页 + try: + retval = urlretrieve(self.url,self.file) + except IOError: + retval = ('***Error: invalid URL: "%s"' % self.url,) + return retval + + def parseAndGetLinks(self): #解析HTML,保存链接 + self.parser = HTMLParser(AbstractFormatter(DumbWriter(StringIO()))) + self.parser.feed(open(self.file).read()) + self.parser.close() + return self.parser.anchorlist + + +class Crawler(object): #管理类,管理整个爬行过程 + + count = 0 #下载网页计数器 + + def __init__ (self,url): + self.q = [url] #链接队列 + self.seen = [] #已下载 + self.dom = urlparse(url)[1] #判断链接是否为主链接的子域名 + + def getPage(self,url): #下载网页 + r = Retriever(url) + retval = r.download() + if retval[0] == "*": #错误,不解析 + print retval,"--- skipping parse" + return + Crawler.count += 1 + print '\n(',Crawler.count,')' + print "URL:",url + print "FILE:",retval[0] + self.seen.append(url) + + links = r.parseAndGetLinks() #得到链接 + for eachLink in links: + if eachLink[:4] != "http" and find(eachLink,"://") == -1: + eachLink = urljoin(url,eachLink) + print "* ",eachLink + + if find(lower(eachLink),"mailto:") != -1: #过滤邮箱链接 + print "--- discarded,mailto link" + continue + + if eachLink not in self.seen: + if find(eachLink,self.dom) == -1: + print "---discarded,not in domain" + else: + if eachLink not in self.q: + self.q.append(eachLink) + print "---new,add to Q" + else: + print "---discarded,already in Q" + else: + print "---discarded, arlready processed" + + def go(self): #在队列里处理链接,启动 + while self.q: + url=self.q.pop() + self.getPage(url) + +def main(): + if len(argv) > 1: + url = argv[1] + + else: + try: + url = raw_input("Enter starting URL:") + except (KeyboardInterrupt,EOFError): + url = "" + + if not url: return + robot = Crawler(url) + robot.go() + +if __name__ == "__main__": + main() + diff --git a/base/3/makeFile.py b/base/3/makeFile.py new file mode 100644 index 0000000..bee369a --- /dev/null +++ b/base/3/makeFile.py @@ -0,0 +1,14 @@ +import os + +filename=raw_input("filename:") +if os.path.exists(filename): + print "file exist" + exit() + + +fd=open(filename,'r') +fd.writelines(all) +fd.close() + +print "done" + diff --git a/base/3/makeTextFile.py b/base/3/makeTextFile.py new file mode 100644 index 0000000..6969f8f --- /dev/null +++ b/base/3/makeTextFile.py @@ -0,0 +1,32 @@ + +'makeTextFile.py -- create text file' + +import os +ls = os.linesep + +#get filename +while True: + fname = raw_input() + if os.path.exists(fname): + print "ERROR: '%s' already exists " %fname + else: + break + +#get file content lines +all = [] +print "\n Enter lines:('.' by itself to quit)\n" + +#loop until user terminates input +while True: + entry = raw_input('>') + if entry == '.': + break + else: + all.append(entry) + +#write lines to file with proper line-ending +fobj = open(fname,'w') +fobj.writelines(['%s%s' %(x,ls) for x in all]) +fobj.close() +print 'DONE!' + diff --git a/base/3/readTextFile.py b/base/3/readTextFile.py new file mode 100644 index 0000000..980d3e0 --- /dev/null +++ b/base/3/readTextFile.py @@ -0,0 +1,17 @@ + +'readTextFile.py -- read and display text file' + +#get filename +fname = raw_input("enter the filename:") +print + +#attempt to open file for reading +try: + fobj = open(fname,'r') +except IOError,e: + print "*** file open error",e +else: + #display contents to the screen + for echoLine in fobj: + print echoLine; +fobj.close() diff --git a/base/4/display.py b/base/4/display.py new file mode 100644 index 0000000..e50f368 --- /dev/null +++ b/base/4/display.py @@ -0,0 +1,11 @@ +def displayType(num): + print num, 'is', + if isinstance(num,(int,long,float,complex)): + print "a number of type:",type(num).__name__ + else: + print "not a number at all" + +displayType(2) +displayType(-1.9) +displayType(-1+1.9j) +displayType('xcxx') diff --git a/base/6/idcheck.py b/base/6/idcheck.py new file mode 100644 index 0000000..b6d6220 --- /dev/null +++ b/base/6/idcheck.py @@ -0,0 +1,20 @@ +import string + +alphas = string.letters +'_' +nums = string.digits + +print "Welcom to the indetifter Checker V1.0" +print "Test must be at least 2 Chars long" +myinput = raw_input("Iddentifter to test:\n") + +if len(myinput) > 1: + if myinput[0] not in alphas: + print "invald: first symbol must be alphbetic" + else: + for otherChar in myinput[1:]: + if alphas not in alphas + nums: + print "invalid:remaining symbols must be alphanumeric" + break + else: + print "ok as an identifier" +raw_input() diff --git a/base/6/queue.py b/base/6/queue.py new file mode 100644 index 0000000..7eb364d --- /dev/null +++ b/base/6/queue.py @@ -0,0 +1,38 @@ + +queue = [] +def enQ(): + queue.append(raw_input("enter new string:").strip()) +def deQ(): + if len(queue) == 0: + print "empty queue\n" + else: + print 'Removed![',`queue.pop()`,']' +def viewQ(): + print queue + +CMDS = {'e': enQ,'d':deQ,'v':viewQ} +def showmenu(): + pr=""" +(E)nqueue +(D)enqueue +(V)iew +(Q)uit + + enter choice: """ + while True: + while True: + try: + choice = raw_input(pr).strip()[0].lower() + except (EOFError,KeyboardInterpt,IndexError): + choice = "q" + print "\nYou picked:[%s]" % choice + if choice not in "devq": + print "error,try again" + else: + break + if choice == "q": + break + CMDS[choice]() +if __name__ == '__main__': + showmenu() + diff --git a/base/6/stack.py b/base/6/stack.py new file mode 100644 index 0000000..60dc053 --- /dev/null +++ b/base/6/stack.py @@ -0,0 +1,43 @@ +stack = [] + +def pushit(): + stack.append(raw_input("enter a string:").strip()) + +def popit(): + if len(stack) == 0: + print "stack is empty!\n" + else: + print 'Removed![',`stack.pop()`,']' + +def viewstack(): + print stack + +CMDS ={'u': pushit,'o':popit,'v':viewstack} + +def showmenu(): + pr = """ + p(U)sh + p(O)p + (V)iew + (Q)uit + + enter the choice: """ + while True: + while True: + try: + choice = raw_input(pr).strip()[0].lower() + except (EOFError,KeyboardInterrupt,IndexError): + choice ="q" + + print "\nYou picked:[%s]" % choice + if choice not in "uovq": + print "Invalid option,try again" + else: + break + + if choice == "q": + break + CMDS[choice]() +if __name__ == "__main__": + showmenu() + diff --git a/base/6/unicode.txt b/base/6/unicode.txt new file mode 100644 index 0000000..f3e8683 --- /dev/null +++ b/base/6/unicode.txt @@ -0,0 +1 @@ +hhhh diff --git a/base/6/unicodeFile.py b/base/6/unicodeFile.py new file mode 100644 index 0000000..0752725 --- /dev/null +++ b/base/6/unicodeFile.py @@ -0,0 +1,20 @@ +''' +An example for unicode string +''' + +CODEC = "utf-8" +FILE = "unicode.txt" + +hello = u"hhhh\n" +byte = hello.encode(CODEC) +f = open(FILE,"w") +f.write(byte) +f.close() + +f = open(FILE,"r") +byte = f.read() +f.close() + +hello = byte.decode(CODEC) +print hello +raw_input() diff --git a/base/7/userpw.py b/base/7/userpw.py new file mode 100644 index 0000000..ebe358e --- /dev/null +++ b/base/7/userpw.py @@ -0,0 +1,53 @@ +db = {} + +def newuser(): + prompt = "login desired:" + while True: + name = raw_input(prompt) + if db.has_key(name): + prompt = "name taken,try again: " + continue + else: + break + pwd = raw_input("passwd:") + db[name]= pwd + print "regeisted oK!\n" + +def olduser(): + name = raw_input("login:") + pwd = raw_input("passwd:") + passwd = db.get(name) + if passwd == pwd: + print "welcome back," ,name + else: + print "login incorrect" + +def showmenu(): + prompt = """ + (n) new user login + (l) exiting user login + (q) quit + enter choice : """ + + done = False + while not done: + chosen = False + while not chosen: + try: + choice = raw_input(prompt).strip()[0].lower() + except(EOFError,KeyboardInterrupt): + choice = "q" + print "\n you picked [%s]" % choice + if choice not in "nlq": + print "invalid option, try again" + else: + chosen = True + + if choice == "q": done = True + if choice == "n": newuser() + if choice == "l": olduser() + +if __name__ == "__main__": + showmenu() + + diff --git a/base/9/ospathex.py b/base/9/ospathex.py new file mode 100644 index 0000000..a333211 --- /dev/null +++ b/base/9/ospathex.py @@ -0,0 +1,38 @@ + +import os +for tmpdir in("/tmp"): + if os.path.isdir(tmpdir): + break + else: + print "no temp dir available" + tmpdir = "" +if tmpdir: + os.chdir(tmpdir) + cwd = os.getcwd() + print " current tmp dir" + print cwd + + print "create example dir" + os.mkdir("example") + os.chdir("example") + cwd = os.getcwd() + print "new work dir" + print cwd + print "list the dir" + print os.listdir(cwd) + + print "create test file" + fobj = open("test","w") + fobj.write("xxg\n") + fobj.write("111111") + fobj.close() + + print "update the list dir" + print os.listdir(cwd) + + print "rename the file" + os.rename("test","xxg.txt") + print os.listdir(cwd) + + + diff --git a/data_struct/binarysearch.py b/data_struct/binarysearch.py new file mode 100644 index 0000000..fa6a1e2 --- /dev/null +++ b/data_struct/binarysearch.py @@ -0,0 +1,25 @@ +def BinarySearch(l,key): + low=0 + high=len(l)-1 + i=0 + while(low <= high): + i = i+1 + mid = low + ((high-low)>>1) + if(l[mid] < key): + low = mid + 1 + elif (l[mid] > key): + high = mid -1 + else: + print "use %d times" % i + return mid + return -1 + +if __name__ == "__main__": + l=[1,4,5,6,7,8,9,44,333,2233] + print l + print BinarySearch(l,4) + print BinarySearch(l,44) + print BinarySearch(l,8) + print BinarySearch(l,2233) + print BinarySearch(l,77) + diff --git a/data_struct/btree.py b/data_struct/btree.py new file mode 100644 index 0000000..69434e8 --- /dev/null +++ b/data_struct/btree.py @@ -0,0 +1,62 @@ +class BTree: + def __init__(self,value): + self.left=None + self.data=value + self.right=None + + def insertLeft(self,value): + self.left=BTree(value) + return self.left + + def insertRight(self,value): + self.right=BTree(value) + return self.right + + def show(self): + print self.data + +def preorder(node): + if node.data: + node.show() + if node.left: + preorder(node.left) + if node.right: + preorder(node.right) + +def inorder(node): + if node.data: + if node.left: + inorder(node.left) + node.show() + if node.right: + inorder(node.right) + +def postorder(node): + if node.data: + if node.left: + postorder(node.left) + if node.right: + postorder(node.right) + node.show() + +if __name__ == "__main__": + + Root=BTree("root") + A=Root.insertLeft("A") + C=A.insertLeft("C") + D=C.insertRight("D") + F=D.insertLeft("F") + G=D.insertRight("G") + B=Root.insertRight("B") + E=B.insertRight("E") + + print "pre-traversal" + preorder(Root) + + print "in-traversal" + inorder(Root) + + print "post-traversal" + postorder(Root) + + diff --git a/data_struct/graph.py b/data_struct/graph.py new file mode 100644 index 0000000..834670b --- /dev/null +++ b/data_struct/graph.py @@ -0,0 +1,35 @@ +def searchGraph(graph,start,end): + results=[] + generatePath(graph,[start],end,results) + results.sort(lambda x,y:cmp(len(x),len(y))) + return results + +def generatePath(graph,path,end,results): + state=path[-1] + if state == end: + results.append(path) + else: + for arc in graph[state]: + if arc not in path: + generatePath(graph,path+[arc],end,results) + + +if __name__ == "__main__": + Graph={ + 'A':['B','C','D'], + 'B':['E'], + 'C':['D','F'], + 'D':['B','E','G'], + 'E':[], + 'F':['D','G'], + 'G':['E'] + } + r = searchGraph(Graph,'A','D') + print "A to D" + for i in r: + print i + + r=searchGraph(Graph,'A','E') + print "A to E" + for i in r: + print i diff --git a/data_struct/queue.py b/data_struct/queue.py new file mode 100644 index 0000000..64da3e4 --- /dev/null +++ b/data_struct/queue.py @@ -0,0 +1,43 @@ +class Queue: + def __init__(self,size=20): + self.queue=[] + self.size=size + self.end=-1 + + def setSize(self,size): + self.size=size + + def In(self,element): + if self.end < self.size -1: + self.queue.append(element) + self.end = self.end + 1 + else: + raise "QueueFull" + + def Out(self): + if self.end != -1: + element = self.queue[0] + self.queue=self.queue[1:] + self.end = self.end-1 + return element + else: + raise "QueueEmpty" + + def End(self): + return self.end + + def empty(self): + self.queue=[] + self.end=-1 + +if __name__ == "__main__": + + queue=Queue() + for i in range(10): + queue.In(i) + print queue.End() + + for i in range(10): + print queue.Out() + + diff --git a/data_struct/sort.py b/data_struct/sort.py new file mode 100644 index 0000000..b190701 --- /dev/null +++ b/data_struct/sort.py @@ -0,0 +1,78 @@ +class BTree: + def __init__(self,value): + self.left=None + self.data=value + self.right=None + + def insertLeft(self,value): + self.left=BTree(value) + return self.left + + def insertRight(self,value): + self.right=BTree(value) + return self.right + + def show(self): + print self.data + +def inorder(node): + if node.data: + if node.left: + inorder(node.left) + node.show() + if node.right: + inorder(node.right) + + +def rinorder(node): + if node.data: + if node.right: + rinorder(node.right) + node.show() + if node.left: + rinorder(node.left) + +def insert(node,value): + if value > node.data: + if node.right: + insert(node.right,value) + else: + node.insertRight(value) + else: + if node.left: + insert(node.left,value) + else: + node.insertLeft(value) + + +if __name__ == "__main__": + + l=[88,11,2,33,22,4,55,33,221,34] + Root=BTree(l[0]) + node=Root + for i in range(1,len(l)): + insert(Root,l[i]) + + print "1---->10" + inorder(Root) + print "10--->1" + rinorder(Root) + + + + + + + + + + + + + + + + + + + diff --git a/data_struct/stack.py b/data_struct/stack.py new file mode 100644 index 0000000..e5b65ce --- /dev/null +++ b/data_struct/stack.py @@ -0,0 +1,59 @@ +class Stack: + def __init__(self,size=20): + self.stack= [] + self.size= size; + self.top= -1 + + def setSize(self,size): + self.size=size; + + def push(self,element): + if self.isFull(): + raise "StackOverflow" + else: + self.stack.append(element) + self.top = self.top + 1 + + def pop(self): + if self.isEmpty(): + raise "StackUnderflow" + else: + element=self.stack[-1] + self.top=self.top-1; + del self.stack[-1] + return element + + def Top(self): + return self.top + + def empty(self): + self.stack=[] + self.top=-1 + + def isEmpty(self): + if self.top == -1: + return True + else: + return False + + def isFull(self): + if self.top == self.size-1: + return True + else: + return False + +if __name__ == "__main__": + + stack=Stack() + + for i in range(10): + stack.push(i) + print stack.Top() + + for i in range(10): + print stack.pop() + + stack.empty() + print stack.Top() + +