console编译 ipython
2014-05-18 11:35:22 hjuj_91 阅读数 3925
```import random
def printBoard(board,score):
for line in board:
#print " ".join(map(str,line))
def transform(x):
if x == "0":
return "_"
else:
return x
print "%5s%5s%5s%5s" % tuple( map(transform,[str(i) for i in line]) )
print "\n\t\tscore : " , score

def initBoard():
global board
board = [[0] * 4 for i in range(4)]
a,b = random.randint(0,3) ,random.randint(0,3)
board[a][b] = 2
a,b = random.randint(0,3) ,random.randint(0,3)
while board[a][b] == 2 :
a,b = random.randint(0,3) ,random.randint(0,3)
board[a][b] = random.choice([2,4])
return board
def inBoard(m,n):
return 0 <= m and m < 4 and 0 <= n and n < 4
def neighbors(i,j):
result = []
directions = [(1,0),(-1,0),(0,1),(0,-1)]
for d in directions:
m,n = i + d[0],j + d[1]
while inBoard(m,n):
if board[m][n] != 0:
result.append(board[m][n])
break
m,n = m + d[0],n + d[1]
return result
def findSameBlock(i,j,direction,markBoard):
global score
m,n = i + direction[0],j + direction[1]
while inBoard(m,n):
if board[m][n] == 0:
m,n = m + direction[0],n+direction[1]
continue
elif board[m][n] != board[i][j]:
return None
elif board[m][n] == board[i][j]:
if markBoard[i][j]: return None
board[i][j] = 0
board[m][n] *= 2
score += board[m][n]
markBoard[m][n] = True
return (m,n)
return None

def merge(direction):
markBoard = [[False] * 4 for i in range(4)]
for i in range(4):
for j in range(4):
if board[i][j] != 0:
findSameBlock(i,j,direction,markBoard)

def detectGameOver():
global win
for i in range(4):
for j in range(4):
num = board[i][j]
if num == 2048 and not win:
print "You Win"
win = True
if num == 0:
return False
for k in neighbors(i,j):
if k == num:
return False
return True
def spawnNewBlock():
a,b = random.randint(0,3) ,random.randint(0,3)
while board[a][b] != 0:
a,b = random.randint(0,3) ,random.randint(0,3)
board[a][b] = random.choice([2,4])
def same(b1,b2):
for i in range(4):
for j in range(4):
if b1[i][j] != b2[i][j]: return False
return True
def move(d):
global board,notChanged
tempBoard = [[0] * 4 for i in range(4)]
cols = [[board[i][0] for i in range(4) if board[i][0] != 0],
[board[i][1] for i in range(4) if board[i][1] != 0],
[board[i][2] for i in range(4) if board[i][2] != 0],
[board[i][3] for i in range(4) if board[i][3] != 0]]
if d == "w":
for i in range(4):
for j in range(len(cols[i])):
tempBoard[j][i] = cols[i][j]
if d == "s":
for k in cols:
k.reverse()
for i in range(4):
for j in range(len(cols[i])):
tempBoard[3 - j][i] = cols[i][j]
rows = [[board[0][i] for i in range(4) if board[0][i] != 0],
[board[1][i] for i in range(4) if board[1][i] != 0],
[board[2][i] for i in range(4) if board[2][i] != 0],
[board[3][i] for i in range(4) if board[3][i] != 0]]
if d == "a":
for i in range(4):
for j in range(len(rows[i])):
tempBoard[i][j] = rows[i][j]
if d == "d":
for k in rows:
k.reverse()
for i in range(4):
for j in range(len(rows[i])):
tempBoard[i][3 - j] = rows[i][j]
#print board
#print tempBoard
notChanged = same(tempBoard,board)
board = tempBoard
def react(key):
handle = {
"w" : (-1, 0),
"a" : (0, -1),
"s" : (1,  0),
"d" : (0,  1)
}
if not handle.has_key(key) : return
merge(handle[key])
move(key)

def __main__():
initBoard()
global board,gameOver,score,notChanged,win
score = 0
gameOver = False
notChanged = False
win = False
while not gameOver:
printBoard(board,score)
key = raw_input().strip()
if key not in "wasd":continue
react(key.strip())
gameOver = detectGameOver()
if not gameOver and not notChanged :spawnNewBlock()
print "\n\nYou Lose!\n\n"

__main__()```

2012-07-13 17:25:04 ssihc0 阅读数 1967

```import win32gui, win32con, win32api

def _MyCallback( hwnd, extra ):
windows = extra;
temp=[];
temp.append(hwnd);
temp.append(win32gui.GetClassName(hwnd));
temp.append(win32gui.GetWindowText(hwnd));
temp.append(hex(hwnd));
windows[hwnd] = temp;

#is_clost =True
def TestEnumWindows(closttitle,is_close):
windows = {};
win32gui.EnumWindows(_MyCallback, windows);
print "Enumerated a total of  windows with %d classes" ,(len(windows))
print '------------------------------';
#print classes
print '-------------------------------';
if is_close :
for item in windows :
if windows[item][1]=="ConsoleWindowClass":
if windows[item][2].endswith(closttitle):
print 111
#  win32gui.CloseWindow(windows[item][0]);
win32gui.SendMessage(windows[item][0], win32con.WM_CLOSE, None, None);
else:
for item in windows :
if windows[item][1]=="ConsoleWindowClass":
if windows[item][2].endswith(closttitle):
#print windows[item][0]
win32gui.ShowWindow(windows[item][0],False);

#print "Enumerating all windows..."
#h=win32gui.FindWindow(None,'\xba\xec\xce\xe5')
#print hex(h)
TestEnumWindows('Regdean.exe',True)
#print "All tests done!"
```

`TestEnumWindows('Regdean.exe',True)`
true 为关闭窗体

false 为隐藏窗体

2017-11-29 14:38:00 weixin_33921089 阅读数 3

import logging

logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")

rootLogger = logging.getLogger()

fileHandler = logging.FileHandler("{0}/{1}.log".format("./", "main"))

fileHandler.setFormatter(logFormatter)

consoleHandler = logging.StreamHandler()

consoleHandler.setFormatter(logFormatter)

rootLogger.warn("sssssss")

'i
2016-01-28 08:31:00 weixin_34221773 阅读数 2

Quite a few problems on Leetcode utilized bitwise operators, especially for those Single Number problem series like this one:

260 . Single Number III
Difficulty: Medium

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
return [3, 5]
Note:
The order of the result is not important. So in the above example, [5, 3]
is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

``````class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
xor = 0
for num in nums:
xor ^= num
musk = 1
while (xor&musk == 0):
musk = musk << 1
a=0
b=0
for num in nums:
if num&musk:
a ^= num
return [a,a^xor]
``````

Before it was accepted, the "time limit exceeded" warning kept pop out. After searching online, I found my answer differs with accepted answer only in the part `musk = musk<<1`, where in my previous answer it was `musk<<1`. Testing `musk<<1` in Canopy Python distribution reveals that value of `musk` didn't change at all. Correct representation should be `musk<<=1`, as analogical to `count += 1`. I guess to eliminate confusion, `musk<<1` is not accepted in Python just like `i++` not accepted neither.

2013-09-25 10:09:00 weixin_34353714 阅读数 4

``````def insert_sort(my_list):
for i in range(1,len(my_list)):
if my_list[i-1] > my_list[i]:
temp = my_list[i]
j=i
while((j>0) & (my_list[j-1]>temp)):
my_list[j] = my_list[j - 1]
j=j-1
my_list[j]=temp

if __name__=="__main__":
my_list=[31,4,6,111,34,22,8,57,90,89,43]
insert_sort(my_list)
print my_list``````

Python Console报错 ：Couldn't connect to console process

【python排序算法 I I】快速排序

2019独角兽企业重金招聘Python工程师标准>>>...

Python学习之 i += 3 与 i = i +3

python编译

python并非完全是解释性语言，它是有编译的，先把源码py文件编译成pyc或者pyo，然后由python的虚拟机执行，相对于py文件来说，编译成pyc和pyo本质上和py没有太大区别，只是对于这个模块的加载速度提高了，并没有提高代码的执行速度，通常情况下不用主动去编译pyc文件，文档上说只要调用了importmodel那么model.py就会先编译成pyc然后加载1.如果需要特殊的

python 编译

2019独角兽企业重金招聘Python工程师标准>>>...