File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- # # Python实现支持向量机
1+ # Python实现支持向量机
22使用Python实现支持向量机,代码思路来源于[ 机器学习实战] ( https://github.com/pbharrin/machinelearninginaction ) 。
33
44# 线性可分支持向量机
Original file line number Diff line number Diff line change 1+ # Python3.5
2+ # 定义一个栈类
3+ class Stack ():
4+ # 栈的初始化
5+ def __init__ (self ):
6+ self .items = []
7+ # 判断栈是否为空,为空返回True
8+ def isEmpty (self ):
9+ return self .items == []
10+ # 向栈内压入一个元素
11+ def push (self , item ):
12+ self .items .append (item )
13+ # 从栈内推出最后一个元素
14+ def pop (self ):
15+ return self .items .pop ()
16+ # 返回栈顶元素
17+ def peek (self ):
18+ return self .items [len (self .items )- 1 ]
19+ # 判断栈的大小
20+ def size (self ):
21+ return len (self .items )
22+
23+ # 栈属性测试
24+ s = Stack ()
25+ print (s .isEmpty ())
26+ s .push (4 )
27+ s .push ('dog' )
28+ print (s .peek ())
29+ s .push (True )
30+ print (s .isEmpty ())
31+ s .push (8.4 )
32+ print (s .pop ())
33+ print (s .pop ())
34+ print (s .size ())
35+
36+ # 利用栈将字串的字符反转
37+ def revstring (mystr ):
38+ # your code here
39+ s = Stack ()
40+ outputStr = ''
41+ for c in mystr :
42+ s .push (c )
43+ while not s .isEmpty ():
44+ outputStr += s .pop ()
45+ return outputStr
46+
47+ print (revstring ('apple' ))
48+ print (revstring ('x' ))
49+ print (revstring ('1234567890' ))
50+
51+ # 利用栈判断括号平衡Balanced parentheses
52+ def parChecker (symbolString ):
53+ s = Stack ()
54+ balanced = True
55+ index = 0
56+ while index < len (symbolString ) and balanced :
57+ symbol = symbolString [index ]
58+ if symbol in '([{' :
59+ s .push (symbol )
60+ else :
61+ if s .isEmpty ():
62+ balanced = False
63+ else :
64+ top = s .pop ()
65+ if not matches (top , symbol ):
66+ balanced = False
67+ index += 1
68+
69+ if balanced and s .isEmpty ():
70+ return True
71+ else :
72+ return False
73+
74+ def matches (open , close ):
75+ opens = '([{'
76+ closers = ')]}'
77+ return opens .index (open ) == closers .index (close )
78+
79+ print (parChecker ('({([()])}){}' ))
80+
81+ # 利用栈将十进制整数转化为二进制整数
82+ def Dec2Bin (decNumber ):
83+ s = Stack ()
84+
85+ while decNumber > 0 :
86+ temp = decNumber % 2
87+ s .push (temp )
88+ decNumber = decNumber // 2
89+ binString = ''
90+ while not s .isEmpty ():
91+ binString += str (s .pop ())
92+ return binString
93+
94+ print (Dec2Bin (42 ))
95+
96+ # 利用栈实现多进制转换
97+ def baseConverter (decNumber , base ):
98+ digits = '0123456789ABCDEF'
99+
100+ s = Stack ()
101+
102+ while decNumber > 0 :
103+ temp = decNumber % base
104+ s .push (temp )
105+ decNumber = decNumber // base
106+
107+ newString = ''
108+ while not s .isEmpty ():
109+ newString = newString + digits [s .pop ()]
110+
111+ return newString
112+
113+ print (baseConverter (59 , 16 ))
You can’t perform that action at this time.
0 commit comments