def run(self): ””’@summary: 重写父类run方法,在线程启动后执行该方法内的代码。
”’
global count
self.lock.acquire()
for i in xrange(10000):
count = count + 1
self.lock.release()
lock = threading.Lock()
for i in range(5):
Counter(lock, “thread-” + str(i)).start()
time.sleep(2) #确保线程都执行完毕
print count
#coding=gbk
import threading, time, random
count = 0
class Counter(threading.Thread):
def __init__(self, lock, threadName): ”’@summary: 初始化对象。
def run(self): ”’@summary: 重写父类run方法,在线程启动后执行该方法内的代码。
”’
global count
self.lock.acquire()
for i in xrange(10000):
count = count + 1
self.lock.release()
lock = threading.Lock()
for i in range(5):
Counter(lock, “thread-” + str(i)).start()
time.sleep(2) #确保线程都执行完毕
print count
import threading, time, random
count = 0
lock = threading.Lock()
def doAdd(): ””’@summary: 将全局变量count 逐一的增加10000。
”’
global count, lock
lock.acquire()
for i in xrange(10000):
count = count + 1
lock.release()
for i in range(5):
threading.Thread(target = doAdd, args = (), name = ‘thread-’ + str(i)).start()
time.sleep(2) #确保线程都执行完毕
print count
import threading, time, random
count = 0
lock = threading.Lock()
def doAdd(): ”’@summary: 将全局变量count 逐一的增加10000。
”’
global count, lock
lock.acquire()
for i in xrange(10000):
count = count + 1
lock.release()
for i in range(5):
threading.Thread(target = doAdd, args = (), name = ‘thread-’ + str(i)).start()
time.sleep(2) #确保线程都执行完毕
print count
import re
import itertools
def solve(puzzle):
words = re.findall('[A-Z]+', puzzle.upper())
unique_characters = set(''.join(words))
assert len(unique_characters) <= 10, 'Too many letters'
first_letters = {word[0] for word in words}
n = len(first_letters)
sorted_characters = ''.join(first_letters) + \
''.join(unique_characters - first_letters)
characters = tuple(ord(c) for c in sorted_characters)
digits = tuple(ord(c) for c in '0123456789')
zero = digits[0]
for guess in itertools.permutations(digits, len(characters)):
if zero not in guess[:n]:
equation = puzzle.translate(dict(zip(characters, guess)))
if eval(equation):
return equation
if __name__ == '__main__':
import sys
for puzzle in sys.argv[1:]:
print(puzzle)
solution = solve(puzzle)
if solution:
print(solution)
you@localhost:~/diveintopython3/examples$ python3 alphametics.py "HAWAII + IDAHO + IOWA + OHIO == STATES"HAWAII + IDAHO + IOWA + OHIO = STATES
510199 + 98153 + 9301 + 3593 == 621246you@localhost:~/diveintopython3/examples$ python3 alphametics.py "I + LOVE + YOU == DORA"I + LOVE + YOU == DORA
1 + 2784 + 975 == 3760you@localhost:~/diveintopython3/examples$ python3 alphametics.py "SEND + MORE == MONEY"SEND + MORE == MONEY
9567 + 1085 == 10652
⁂
找到一个模式所有出现的地方
字母算术谜题解决者做的第一件事是找到谜题中所有的字母(A–Z)。
>>> import re>>> re.findall('[0-9]+', '16 2-by-4s in rows of 8') ①
['16', '2', '4', '8']>>> re.findall('[A-Z]+', 'SEND + MORE == MONEY') ②
['SEND', 'MORE', 'MONEY']
re 模块是正则表达式的Python实现。它有一个漂亮的函数findall(),接受一个正则表达式和一个字符串作为参数,然后找出字符串中出现该模式的所有地方。在这个例子里,模式匹配的是数字序列。findall()函数返回所有匹配该模式的子字符串的列表。
>>> assert 1 + 1 == 2 ①
>>> assert 1 + 1 == 3 ②
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError>>> assert 2 + 2 == 5, "Only for very large values of 2" ③
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Only for very large values of 2
>>> unique_characters = {'E', 'D', 'M', 'O', 'N', 'S', 'R', 'Y'}>>> gen = (ord(c) for c in unique_characters) ①
>>> gen ②
<generator object <genexpr> at 0x00BADC10>>>> next(gen) ③
69>>> next(gen)68>>> tuple(ord(c) for c in unique_characters) ④
(69, 68, 77, 79, 78, 83, 82, 89)
如果你愿意,你可以将生成器表达式传给tuple(), list(), 或者 set()来迭代所有的值并且返回元组,列表或者集合。在这种情况下,你不需要一对额外的括号 — 将生成器表达式ord(c) for c in unique_characters 传给 tuple() 函数就可以了, Python 会推断出它是一个生成器表达式。
…continuing from the previous interactive shell…
>>> import itertools>>> groups = itertools.groupby(names, len) ①
>>> groups<itertools.groupby object at 0x00BB20C0>>>> list(groups)[(4, <itertools._grouper object at 0x00BA8BF0>),
(5, <itertools._grouper object at 0x00BB4050>),
(6, <itertools._grouper object at 0x00BB4030>)]>>> groups = itertools.groupby(names, len) ②
>>> for name_length, name_iter in groups: ③
... print('Names with {0:d} letters:'.format(name_length))... for name in name_iter:... print(name)... Names with 4 letters:
Alex
Anne
Dora
John
Mike
Names with 5 letters:
Chris
Ethan
Sarah
Names with 6 letters:
Lizzie
Wesley
characters = tuple(ord(c) for c in sorted_characters)
digits = tuple(ord(c) for c in '0123456789')
...
for guess in itertools.permutations(digits, len(characters)):
...
equation = puzzle.translate(dict(zip(characters, guess)))
>>> import subprocess>>> eval("subprocess.getoutput('ls ~')") ①
'Desktop Library Pictures \
Documents Movies Public \
Music Sites'>>> eval("subprocess.getoutput('rm /some/random/file')") ②
>>> x = 5>>> eval("x * 5", {}, {}) ①
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'x' is not defined>>> eval("x * 5", {"x": x}, {}) ②
>>> import math>>> eval("math.sqrt(x)", {"x": x}, {}) ③
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'math' is not defined
>>> eval("__import__('math').sqrt(5)",... {"__builtins__":None}, {}) ①
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name '__import__' is not defined>>> eval("__import__('subprocess').getoutput('rm -rf /')",... {"__builtins__":None}, {}) ②
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name '__import__' is not defined
import re
import itertools
def solve(puzzle):
words = re.findall('[A-Z]+', puzzle.upper())
unique_characters = set(''.join(words))
assert len(unique_characters) <= 10, 'Too many letters'
first_letters = {word[0] for word in words}
n = len(first_letters)
sorted_characters = ''.join(first_letters) + \
''.join(unique_characters - first_letters)
characters = tuple(ord(c) for c in sorted_characters)
digits = tuple(ord(c) for c in '0123456789')
zero = digits[0]
for guess in itertools.permutations(digits, len(characters)):
if zero not in guess[:n]:
equation = puzzle.translate(dict(zip(characters, guess)))
if eval(equation):
return equation
if __name__ == '__main__':
import sys
for puzzle in sys.argv[1:]:
print(puzzle)
solution = solve(puzzle)
if solution:
print(solution)
you@localhost:~/diveintopython3/examples$ python3 alphametics.py "HAWAII + IDAHO + IOWA + OHIO == STATES"HAWAII + IDAHO + IOWA + OHIO = STATES
510199 + 98153 + 9301 + 3593 == 621246you@localhost:~/diveintopython3/examples$ python3 alphametics.py "I + LOVE + YOU == DORA"I + LOVE + YOU == DORA
1 + 2784 + 975 == 3760you@localhost:~/diveintopython3/examples$ python3 alphametics.py "SEND + MORE == MONEY"SEND + MORE == MONEY
9567 + 1085 == 10652
⁂
找到一个模式所有出现的地方
字母算术谜题解决者做的第一件事是找到谜题中所有的字母(A–Z)。
>>> import re>>> re.findall('[0-9]+', '16 2-by-4s in rows of 8') ①
['16', '2', '4', '8']>>> re.findall('[A-Z]+', 'SEND + MORE == MONEY') ②
['SEND', 'MORE', 'MONEY']
re 模块是正则表达式的Python实现。它有一个漂亮的函数findall(),接受一个正则表达式和一个字符串作为参数,然后找出字符串中出现该模式的所有地方。在这个例子里,模式匹配的是数字序列。findall()函数返回所有匹配该模式的子字符串的列表。
>>> assert 1 + 1 == 2 ①
>>> assert 1 + 1 == 3 ②
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError>>> assert 2 + 2 == 5, "Only for very large values of 2" ③
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Only for very large values of 2
>>> unique_characters = {'E', 'D', 'M', 'O', 'N', 'S', 'R', 'Y'}>>> gen = (ord(c) for c in unique_characters) ①
>>> gen ②
<generator object <genexpr> at 0x00BADC10>>>> next(gen) ③
69>>> next(gen)68>>> tuple(ord(c) for c in unique_characters) ④
(69, 68, 77, 79, 78, 83, 82, 89)
如果你愿意,你可以将生成器表达式传给tuple(), list(), 或者 set()来迭代所有的值并且返回元组,列表或者集合。在这种情况下,你不需要一对额外的括号 — 将生成器表达式ord(c) for c in unique_characters 传给 tuple() 函数就可以了, Python 会推断出它是一个生成器表达式。
…continuing from the previous interactive shell…
>>> import itertools>>> groups = itertools.groupby(names, len) ①
>>> groups<itertools.groupby object at 0x00BB20C0>>>> list(groups)[(4, <itertools._grouper object at 0x00BA8BF0>),
(5, <itertools._grouper object at 0x00BB4050>),
(6, <itertools._grouper object at 0x00BB4030>)]>>> groups = itertools.groupby(names, len) ②
>>> for name_length, name_iter in groups: ③
... print('Names with {0:d} letters:'.format(name_length))... for name in name_iter:... print(name)... Names with 4 letters:
Alex
Anne
Dora
John
Mike
Names with 5 letters:
Chris
Ethan
Sarah
Names with 6 letters:
Lizzie
Wesley
characters = tuple(ord(c) for c in sorted_characters)
digits = tuple(ord(c) for c in '0123456789')
...
for guess in itertools.permutations(digits, len(characters)):
...
equation = puzzle.translate(dict(zip(characters, guess)))
>>> import subprocess>>> eval("subprocess.getoutput('ls ~')") ①
'Desktop Library Pictures \
Documents Movies Public \
Music Sites'>>> eval("subprocess.getoutput('rm /some/random/file')") ②
>>> x = 5>>> eval("x * 5", {}, {}) ①
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'x' is not defined>>> eval("x * 5", {"x": x}, {}) ②
>>> import math>>> eval("math.sqrt(x)", {"x": x}, {}) ③
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'math' is not defined
>>> eval("__import__('math').sqrt(5)",... {"__builtins__":None}, {}) ①
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name '__import__' is not defined>>> eval("__import__('subprocess').getoutput('rm -rf /')",... {"__builtins__":None}, {}) ②
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name '__import__' is not defined