Snake's Home

snake


  • 首頁

  • 歸檔

  • 標籤
Snake's Home

调用微信接口实现测试监控

發表於 2016-08-01 | 分類於 python

本文发布在 调用微信接口实现测试监控

最近写了些东东,来监控各种异常。传统的发邮件时效性不太好,更何况每天那么多邮件。
想到用微信的企业号来发消息。最重要一点,它是免费的。

首先要注册一个账号:
here

选择企业号

要填手机号,(微信需要绑定银行卡),扫描一下。

填写完公众号信息,就差不多看到曙光了。

创建一个应用,本人选择的是消息型

设置管理员:
指定应用的管理员。点击设置-> 权限管理 -> 管理 -> 新建管理组 –> 添加管理员和权限。然后就会获得corpid 和 sceret。记录下来,这个很重要。后面代码中用得到。

然后就是敲代码了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/python
# coding=utf-8
import sys
import urllib2
import time
import json
import requests

__author__ = 'anderson'

reload(sys)
sys.setdefaultencoding('utf-8')

CORPID = "wx1817a90bedc96275"
CORPSECRET = "cL30j1u2kuPvDo3QJuZCV6IOrBNKsUKRkI5Wo_3Aru_mkOIePs2Jso83BWzz93o-"
BASEURL = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}'.format(CORPID, CORPSECRET)
URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s"


class Token(object):
# get token
def __init__(self):

self.expire_time = sys.maxint

def get_token(self):
if self.expire_time > time.time():
request = urllib2.Request(BASEURL)
response = urllib2.urlopen(request)
result_string = response.read().strip()
result_json = json.loads(result_string)
if 'errcode' in result_json.keys():
print >> result_json['errmsg'], sys.stderr
sys.exit(1)
self.expire_time = time.time() + result_json['expires_in']
self.access_token = result_json['access_token']
return self.access_token


def send_message(title, content):
team_token = Token().get_token()
print team_token
url = URL % (team_token)
wechat_json = {
"toparty": "1",
"msgtype": "text",
"agentid": "1",
"text": {
"content": "title:{0}\n content:{1}".format(title, content)
},
"safe": "0"
}
response = requests.post(url, data=json.dumps(wechat_json, ensure_ascii=False, encoding='utf8'))
print response.json()


if __name__ == '__main__':
send_message("test", "just test")

运行一下,就可以收到消息了:

可以设置各种群组,接收消息的人。
结合Jenkins, 灵活运用到测试中来

Snake's Home

json_load_dump

發表於 2016-07-29 | 分類於 python

在程序运行的过程中,所有的变量都是在内存中,比如,定义一个dict:

1
d = dict(name='Bob', age=20, score=88)

首先,我们尝试把一个对象序列化并写入文件:

1
2
3
>>> d = dict(name='Bob', age=20, score=88)
>>> pickle.dumps(d)
"(dp0\nS'age'\np1\nI20\nsS'score'\np2\nI88\nsS'name'\np3\nS'Bob'\np4\ns."

pickle.dumps()方法把任意对象序列化成一个str,然后,就可以把这个str写入文件。或者用另一个方法pickle.dump()直接把对象序列化后写入一个file-like Object:

1
2
3
>>> f = open('dump.txt', 'wb')
>>> pickle.dump(d, f)
>>> f.close()

看看写入的dump.txt文件,一堆乱七八糟的内容,这些都是Python保存的对象内部信息。

当我们要把对象从磁盘读到内存时,可以先把内容读到一个str,然后用pickle.loads()方法反序列化出对象,也可以直接用pickle.load()方法从一个file-like Object中直接反序列化出对象。我们打开另一个Python命令行来反序列化刚才保存的对象:

1
2
3
4
5
>>> f = open('dump.txt', 'rb')
>>> d = pickle.load(f)
>>> f.close()
>>> d
{'age': 20, 'score': 88, 'name': 'Bob'}

变量的内容又回来了!

JSON

如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。

JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下:

JSON类型 Python类型
{} dict
[] list
“string” ‘str’或u’unicode’
1234.56 int或float
true/false True/False
null None
Python内置的json模块提供了非常完善的Python对象到JSON格式的转换。我们先看看如何把Python对象变成一个JSON:

1
2
3
4
>>> import json
>>> d = dict(name='Bob', age=20, score=88)
>>> json.dumps(d)
'{"age": 20, "score": 88, "name": "Bob"}'

dumps()方法返回一个str,内容就是标准的JSON。类似的,dump()方法可以直接把JSON写入一个file-like Object。

要把JSON反序列化为Python对象,用loads()或者对应的load()方法,前者把JSON的字符串反序列化,后者从file-like Object中读取字符串并反序列化:

1
2
3
>>> json_str = '{"age": 20, "score": 88, "name": "Bob"}'
>>> json.loads(json_str)
{u'age': 20, u'score': 88, u'name': u'Bob'}

有一点需要注意,就是反序列化得到的所有字符串对象默认都是unicode而不是str。由于JSON标准规定JSON编码是UTF-8,所以我们总是能正确地在Python的str或unicode与JSON的字符串之间转换。

总结:

dumps()方法返回一个str,内容就是标准的JSON。
loads()把JSON反序列化为Python对象

Snake's Home

PYTHON-编码处理小结

發表於 2016-07-28 | 分類於 python

原文

用python处理中文时,读取文件或消息,http参数等等

一运行,发现乱码(字符串处理,读写文件,print)

然后,大多数人的做法是,调用encode/decode进行调试,并没有明确思考为何出现乱码

所以调试时最常出现的错误

错误1

1
2
3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)

错误2

1
2
3
4
5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

首先

必须有大体概念,了解下字符集,字符编码

ASCII | Unicode | UTF-8 | 等等

str 和 unicode

str和unicode都是basestring的子类

所以有判断是否是字符串的方法

1
2
def is_str(s):
return isinstance(s, basestring)
1
2
str  -> decode('the_coding_of_str') -> unicode
unicode -> encode('the_coding_you_want') -> str

str是字节串,由unicode经过编码(encode)后的字节组成的

1
2
3
4
5
s = '中文'
s = u'中文'.encode('utf-8')

>>> type('中文')
<type 'str'>

求长度(返回字节数)

1
2
3
4
>>> u'中文'.encode('utf-8')
'\xe4\xb8\xad\xe6\x96\x87'
>>> len(u'中文'.encode('utf-8'))
6

unicode才是真正意义上的字符串,由字符组成

声明方式

1
2
3
4
5
6
7
8
9
10
11
12
s = u'中文'
s = '中文'.decode('utf-8')
s = unicode('中文', 'utf-8')

type(u'中文')
<type 'unicode'>
求长度(返回字符数),在逻辑中真正想要用的

>>> u'中文'
u'\u4e2d\u6587'
>>> len(u'中文')
2

结论:
搞明白要处理的是str还是unicode, 使用对的处理方法(str.decode/unicode.encode)

下面是判断是否为unicode/str的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> isinstance(u'中文', unicode)
True
>>> isinstance('中文', unicode)
False

>>> isinstance('中文', str)
True
>>> isinstance(u'中文', str)
False
简单原则:不要对str使用encode,不要对unicode使用decode (事实上可以对str进行encode的,具体见最后,为了保证简单,不建议)

>>> '中文'.encode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)

>>> u'中文'.decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

不同编码转换,使用unicode作为中间编码

1
2
#s是code_A的str
s.decode('code_A').encode('code_B')

总结总结,本文仅适用于python2.x

默认编码与开头声明
首先是开头的地方声明编码

1
# coding: utf8

这个东西的用处是声明文件编码为utf8(要写在前两行内),不然文件里如果有中文,比如

a = ‘美丽’
b = u’美丽’
中任何一种,运行前就会提示你SyntaxError,Non-ASCII character… 之类,因为python2.x的文件编码默认使用万恶的ascii
开头加上那句默认编码声明就会变成utf8,获取当前的默认编码

sys.getdefaultencoding()
unicode与utf8
在python中,使用unicode类型作为编码的基础类型,编解码要以其为中间形式过渡,即进行str和unicode之间的转换。
解码然后再编码的过程,即str->unicode->str的过程。中间得到的叫做unicode对象

这里需要强调的是unicode是一种字符编码方法,是 “与存储无关的表示”,而utf8是一种以unicode进行编码的计算机二进制表示,或者说传输规范。gbk,gb2312,gb18030, utf8等属于不同的字符集,转换编码就是在它们中的任意两者间进行。

控制台的编码

这又是另一个让人困惑的地方——控制台的编码导致的乱码问题甚至是报错。一般个人用的电脑上控制台基本上都是utf8编码的

一般submine保存时需要选择“utf-8 with Bom”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#encode=utf-8
import json

data1 = {'b': 789, 'c': 456, 'a': 123}
encode_json = json.dumps(data1)
print type(encode_json), encode_json

decode_json = json.loads(encode_json)
print type(decode_json)
print decode_json['a']
print decode_json
print json.dumps(decode_json)

s='中国'
#s.encode('gbk')

print s
Snake's Home

changehost

發表於 2016-06-04 | 分類於 python

最近写了一个自动修改host文件的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#encoding=utf-8
import os
import re
import time
import platform

host_window = r"C:\Windows\System32\drivers\etc\hosts"
host_mac = r"/etc/hosts"
B2B_UAT_HOST = ["#B2B uat deepblue2",
'10.128.34.183 uat.englishtown.com',
'10.128.34.183 uat-cache.englishtown.com',
'10.128.34.233 uatdeepblue2.englishtown.com',
'10.128.34.233 uatdeepblue2cn.englishtown.com']

HOST_LIVE = ["#LIVE",
"104.20.43.137 englishlive.ef.com",
"104.20.43.137 www.englishtown.com",
"104.20.43.137 www.englishtown.com.br",
"104.20.43.137 services.englishtown.com",
"104.20.43.137 etvt.englishtown.com",
"104.20.43.137 axis.englishtown.com",
"104.20.43.137 secure.englishtown.com",
"104.20.43.137 accenture.englishtown.com",
"104.20.43.137 accounts.ef.com"]

def search_host(hostvalue,host_path):
hostfile = open(host_path,'r')
each_line = hostfile.readlines()
hostfile.close()
findresult = re.findall(hostvalue,''.join(each_line))
return findresult

def write_host(hostvalue,host_path):

output = open(host_path, 'a')

for insid in hostvalue:
print insid
output.write(insid)
output.write("\n")
output.close()

if __name__ == "__main__":
#inside_test()
if platform.system is "Windows":
host_path = host_window
else:
host_path = host_mac
os.popen("sudo chmod 777 %s" %host_path)

print host_path
if search_host(HOST_LIVE[0],host_path):
print ("Already exist")
pass
else:
write_host(HOST_LIVE,host_path)
Snake's Home

nodejswritefile

發表於 2016-06-04 | 分類於 js

最近在搞一个网站,用 javascript 写东西,发现用js来读写本地文件不是很方便, 用nodejs效果更佳。

网上找的例子。

filestream读写本地文件

1、filestream API

  • 读文件:fs.readFile(异步)
  • 写文件:fs.writeFile(异步)
  • 追加内容:fs.appendFile(异步)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 引用 fs(filestream) 模块
var fs = require("fs");

// 1、读文件
fs.readFile("text.txt", function (error, fileData) {
if (error) {
// 出现错误
}
// 操作fileData
});

// 2、写文件
fs.writeFiel("text.txt", "new fileData", function (error) {
if (error) {
// 出现错误
}
// 继续操作
});

// 3、追加内容
fs.appendFile("text.txt", "append fileData", function (error) {
if (error) {
// 出现错误
}
// 继续操作
});

2、集成例子

通过访问不同的querystring来操作不同的API:

  • localhost:2014?read => 读文件
  • localhost:2014?write => 写文件
  • localhost:2014?append => 追加内容

例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// 引用 http 模块
var http = require("http");

// 引用 filestream 模块
var fs = require("fs");

// 引用 url 模块
var url = require("url")

// 引用 querystring 模块
var querystring = require("querystring")

http.createServer(function (request, response) {
var objQuery = querystring.parse(url.parse(request.url).query);

// 读取文件
if (objQuery.type == "read") {
// 为什么不是 fs.read
fs.readFile("./tmp/file.txt", function (error, fileData) {
if (error) {
write(response, "<h1>读取出现错误</h1>");
} else {
write(response, "<h1>读取内容为:</h1>" + fileData);
}
});
}
// 写入文件
else if (objQuery.type == "write") {
var writeString = "\n" + Date.now();
fs.writeFile("./tmp/file.txt", writeString, function (error) {
if (error) {
write(response, "<h1>写入出现错误</h1>");
} else {
write(response, "<h1>写入内容为:</h1>" + writeString);
}
});
}
// 追加内容
else if (objQuery.type == "append") {
var appendString = "\n" + Date.now();
fs.appendFile("./tmp/file.txt", appendString, function (error) {
if (error) {
write(response, "<h1>追加出现错误</h1>");
} else {
write(response, "<h1>追加内容为:</h1>" + appendString);
}
});
} else {
write(response, "<h1>请在网址上输入参数</h1>");
}
}).listen(2014);

function write(response, content) {
response.writeHead(200, {
"content-type": "text/html"
});
response.write(content);
response.end();
}

3. node.js里面怎么创建和解析JSON格式的文件

1
2
3
4
5
6
7
8
var fs = require('fs');

var writlog = {"rows":[ {"buildid":"data.number","product":"englishtown","env":"live","version":"ver"}
]}

fs.writeFileSync('./output.json',JSON.stringify(writlog));

var JsonObj=JSON.parse(fs.readFileSync('./output.json'));console.log(JsonObj);
Snake's Home

stock

發表於 2016-05-04

get information:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# encoding:utf8
import urllib2
import os
import threading
import json

# 从文件中读取股票代码
def readCode(filename, codes):
f = open(filename, "r")
for line in f.readlines():
line.strip()
codes.append(line)
f.close()

# 根据股票代码获取股票的当日信息,信息格式为
# 0:”大秦铁路”,股票名字;
# 1:”27.55″,今日开盘价;
# 2:”27.25″,昨日收盘价;
# 3:”26.91″,当前价格;
# 4:”27.55″,今日最高价;
# 5:”26.20″,今日最低价;
# 6:”26.91″,竞买价,即“买一”报价;
# 7:”26.92″,竞卖价,即“卖一”报价;
# 8:”22114263″,成交的股票数,由于股票交易以一百股为基本单位,所以在使用时,通常把该值除以一百;
# 9:”589824680″,成交金额,单位为“元”,为了一目了然,通常以“万元”为成交金额的单位,所以通常把该值除以一万;
# 10:”4695″,“买一”申请4695股,即47手;
# 11:”26.91″,“买一”报价;
# 12:”57590″,“买二”
# 13:”26.90″,“买二”
# 14:”14700″,“买三”
# 15:”26.89″,“买三”
# 16:”14300″,“买四”
# 17:”26.88″,“买四”
# 18:”15100″,“买五”
# 19:”26.87″,“买五”
# 20:”3100″,“卖一”申报3100股,即31手;
# 21:”26.92″,“卖一”报价
# (22, 23), (24, 25), (26,27), (28, 29)分别为“卖二”至“卖四的情况”
# 30:”2008-01-11″,日期;
# 31:”15:05:32″,时间;
#
def getComInfo(code):
# 抓取股票信息
url = "http://hq.sinajs.cn/list=%s" % code
response = urllib2.urlopen(url)
javascriptInfo = response.read()
# 解析成python可识别的信息
pythonInfo = javascriptInfo[4:]
exec(pythonInfo)
company = "hq_str_" + code
companyInfo = eval(company)
companyInfo = companyInfo.split(",")
# 部分股票由于特殊情况没有相应信息
if len(companyInfo) < 3:
return
currentPrice = companyInfo[3]
# 当前票价小于5元时保存
if float(currentPrice) < 5.0:
saveGoodTicket(code)
print code, companyInfo[0]

# 保存好的股票日K线
def saveGoodTicket(code):
# # 日K线
# url = "http://image.sinajs.cn/newchart/daily/n/%s.gif" % code
# # 周K线
# url = "http://image.sinajs.cn/newchart/weekly/n/%s.gif" % code
# 月K线
url = "http://image.sinajs.cn/newchart/monthly/n/%s.gif" % code
# 分时线
# url = "http://image.sinajs.cn/newchart/min/n/%s.gif" % code
try:
response = urllib2.urlopen(url)
data = response.read()
f = open("goodTicket/" + code +'.gif', "wb")
f.write(data)
f.close()
except Exception, e:
print e
finally:
pass

# 单个线程进行的工作
def singleHandle(codes, test):
print test
for code in codes:
# 去除code中的空白字符
code = code.strip()
# 获取信息
getComInfo(code)

# 每次四个线程获取股票信息
def multiHandle(fourcodes, test):
threads = [threading.Thread(target=singleHandle, args=(codes, test)) for codes in fourcodes]
for t in threads:
t.start()
for t in threads:
t.join()

if __name__ == '__main__':
codes = []
readCode("codes.txt", codes)
num = len(codes)
if not os.path.isdir("goodTicket"):
os.mkdir("goodTicket")
print "make dir pic"

# 设置4个线程
threadLen = num / 4

t1 = codes[0: threadLen]
t2 = codes[threadLen : threadLen*2]
t3 = codes[threadLen*2 : threadLen *3]
t4 = codes[threadLen*3 : ]
t = [t1, t2, t3, t4]
multiHandle(t, "To Beautiful You")

print "success"

generatehtml.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# encoding=utf8
import os
htmlHead = '''
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html>
</head>
<body>
{{BODY}}
</body>
</html>
'''

if __name__ == '__main__':
files = os.listdir("goodTicket")
htmlBody = "<ul>"
for filename in files:
htmlBody = htmlBody + "<li><img src=\"%s\"></li>" % ("goodTicket/" + filename)

htmlBody = htmlBody + "</ul>"

html = htmlHead.replace("{{BODY}}", htmlBody)
f = open("pic.html", "w")
f.write(html)
f.close()
Snake's Home

bootstrap+node一天快速建一个网站

發表於 2016-04-27 | 分類於 nodejs

最近下载了好几个 bootstrap 的模版, 用nodejs跑起来。
一般用express框架。
结构如下:

1
2
3
4
5
6
7
8
9
-- lib
-- views
+ -- index.html
+ -- about.html
+ -- contact.html
+ -- 404.html
-- node_modules
+ -- express
package.json

先配置 Package.json(类似ruby rails 中的Gem file)

1
2
3
4
5
6
7
8
9
10
{
"name" : "website-using-express",
"version" : "0.0.1",
"scripts" : {
"start" : "node Server.js"
},
"dependencies" : {
"express" : "latest"
}
}

然后Switch to your project folder and type

install``` (类似gem install)
1

接着建立Server.js
express里面一般都是 app.js

```javascript
var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';

router.use(function (req,res,next) {
  console.log("/" + req.method);
  next();
});

router.get("/",function(req,res){
  res.sendFile(path + "index.html");
});

router.get("/about",function(req,res){
  res.sendFile(path + "about.html");
});

router.get("/contact",function(req,res){
  res.sendFile(path + "contact.html");
});

app.use("/",router);

app.use("*",function(req,res){
  res.sendFile(path + "404.html");
});

app.listen(3000,function(){
  console.log("Live at Port 3000");
});

各种配置和路由,express会把这放在router里面去做。
建一个views的文件夹,把html放里面,然后在这个里面相应的链接一下。
然后敲上

start``` (rails start)
1
在浏览器里面敲上 localhost:3000 (端口靠js里面设置)

结果没起来,因为把 css, js, image等放到public 下了。

解决方法:
模板文件默认存放在views子目录。这时,如果要在网页中加载静态文件(比如样式表、图片等),就需要另外指定一个存放静态文件的目录。
```app.use(express.static('public'));

上面代码在文件app.js之中,指定静态文件存放的目录是public。于是,当浏览器发出非HTML文件请求时,服务器端就到public目录寻找这个文件。比如,浏览器发出如下的样式表请求:

1
<link href="/bootstrap/css/bootstrap.css" rel="stylesheet">

服务器端就到public/bootstrap/css/目录中寻找bootstrap.css文件。

然后就跑起来了。
后面研究下数据库等。

参考:
expressjs-and-bootstrap

Express框架

Snake's Home

算法

發表於 2016-04-12 | 分類於 python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#coding=utf-8

class Node(object):
"""节点类"""
def __init__(self, elem=-1, lchild=None, rchild=None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild


class Tree(object):
"""树类"""
def __init__(self):
self.root = Node()


def add(self, elem):
"""为树添加节点"""
node = Node(elem)
if self.root.elem == -1: #如果树是空的,则对根节点赋值
self.root = node
else:
myQueue = []
treeNode = self.root
myQueue.append(treeNode)
while myQueue: #对已有的节点进行层次遍历
treeNode = myQueue.pop(0)
if treeNode.lchild == None:
treeNode.lchild = node
return
elif treeNode.rchild == None:
treeNode.rchild = node
return
else:
myQueue.append(treeNode.lchild)
myQueue.append(treeNode.rchild)


def front_digui(self, root):
"""利用递归实现树的先序遍历"""
if root == None:
return
print root.elem,
self.front_digui(root.lchild)
self.front_digui(root.rchild)


def middle_digui(self, root):
"""利用递归实现树的中序遍历"""
if root == None:
return
self.middle_digui(root.lchild)
print root.elem,
self.middle_digui(root.rchild)


def later_digui(self, root):
"""利用递归实现树的后序遍历"""
if root == None:
return
self.later_digui(root.lchild)
self.later_digui(root.rchild)
print root.elem,


def front_stack(self, root):
"""利用堆栈实现树的先序遍历"""
if root == None:
return
myStack = []
node = root
while node or myStack:
while node: #从根节点开始,一直找它的左子树
print node.elem,
myStack.append(node)
node = node.lchild
node = myStack.pop() #while结束表示当前节点node为空,即前一个节点没有左子树了
node = node.rchild #开始查看它的右子树


def middle_stack(self, root):
"""利用堆栈实现树的中序遍历"""
if root == None:
return
myStack = []
node = root
while node or myStack:
while node: #从根节点开始,一直找它的左子树
myStack.append(node)
node = node.lchild
node = myStack.pop() #while结束表示当前节点node为空,即前一个节点没有左子树了
print node.elem,
node = node.rchild #开始查看它的右子树


def later_stack(self, root):
"""利用堆栈实现树的后序遍历"""
if root == None:
return
myStack1 = []
myStack2 = []
node = root
myStack1.append(node)
while myStack1: #这个while循环的功能是找出后序遍历的逆序,存在myStack2里面
node = myStack1.pop()
if node.lchild:
myStack1.append(node.lchild)
if node.rchild:
myStack1.append(node.rchild)
myStack2.append(node)
while myStack2: #将myStack2中的元素出栈,即为后序遍历次序
print myStack2.pop().elem,


def level_queue(self, root):
"""利用队列实现树的层次遍历"""
if root == None:
return
myQueue = []
node = root
myQueue.append(node)
while myQueue:
node = myQueue.pop(0)
print node.elem,
if node.lchild != None:
myQueue.append(node.lchild)
if node.rchild != None:
myQueue.append(node.rchild)


if __name__ == '__main__':
"""主函数"""
elems = range(10) #生成十个数据作为树节点
tree = Tree() #新建一个树对象
for elem in elems:
tree.add(elem) #逐个添加树的节点

print '队列实现层次遍历:'
tree.level_queue(tree.root)

print '\n\n递归实现先序遍历:'
tree.front_digui(tree.root)
print '\n递归实现中序遍历:'
tree.middle_digui(tree.root)
print '\n递归实现后序遍历:'
tree.later_digui(tree.root)

print '\n\n堆栈实现先序遍历:'
tree.front_stack(tree.root)
print '\n堆栈实现中序遍历:'
tree.middle_stack(tree.root)
print '\n堆栈实现后序遍历:'
tree.later_stack(tree.root)
Snake's Home

所谓管理

發表於 2016-04-12 | 分類於 职业

最近心比较累。

突然明白了:

大公司所谓的管理,

管理,就是培植自己的嫡系,打击别人的亲信,关键岗位能放自己的人。每个人都会被各个圈子争取,面临站队。就看你是否站错队。风水也是轮流转的。当你对任何人都不构成威胁时,你就有独善其身的机会,也就意味着你难以出头。只有你领导上去你,才有可能带你玩。有人的地方就有江湖,江湖险恶,没有人会无缘无故对你好,就看你有无利用价值,或者对手是否在争夺你。每个人都是伪装者,开始各种表演,时间长了,情商再低的人也能看出来。斗争越激烈,说明你位置越高,或者你对手情商高。没有赢家,也没有结局,要么出局,要么有小弟替你背锅出局。可悲的是有些出局的小弟,被你当枪使了仍对你感激。影帝啊!

Snake's Home

看美剧

發表於 2016-04-12

工作是英文环境。要跟老外交流。

自己蹩脚的口语,总是阻碍了表达。然后很难理解外国人的幽默。

上次看到有人发帖说去苹果面试,口语要求很高。然后他的经验是看美剧来提高。

于是我也开始看美剧“摩登家庭”。

感觉就是讲得很快。然后很多简单的单词表达了复杂的意思。

当我们讲的时候,想破头的去想一个专业单词来表达。

然后有的时候发现还有点意思,有些小幽默,然后发音。

最主要的是一些日常生活单词,课本上是学不到的。

听了几次后,我有那种想说英语的欲望了。

坚持!加油!

123…7
Snake

Snake

不要被困难击倒,除非你躺着睡大觉

69 文章
17 分類
57 標籤
© 2017 Snake
由 Hexo 強力驅動
主題 - NexT.Muse