⑴ python 判斷問題
你這問題不難,但是要完全寫出來還是需要一點時間。給你一個參考代碼,你可以參照這個思路自己寫。
參考代碼說明:對比兩個Excel中數據,每個Excel中數據有兩列組成,代碼列和名稱列。用Python讀成字典,先比較代碼列是否相等,如果不等列印出來;如果代碼一樣名稱不一樣,也列印出來。
# -*- coding: utf-8 -*-
import xlrd
import xlwt
from xlutils. import
import os,time
import operator
path = r"E:\xx"
#path = raw_input('Input Path: ')
os.chdir(path)
print "Current Workspace: %s"%os.getcwd()
#讀取excel工作表中數據為字典
#字典形式為:{代碼:地名}
def readDictStandard():
#name_check = raw_input('Check Excel Name: ')
filename = (name_check).decode('cp936')
data = xlrd.open_workbook(filename + '.xls',formatting_info = True)
table = data.sheet_by_index(0)
#table = data.sheet_by_name(u'di')
print table.name
cellList_k = []
cellList_v = []
ncols = table.ncols
for col in range(0,ncols):
if not (col % 2):
collist_k = table.col_values(col)
collist_v = table.col_values(col+1)
for cell_k in collist_k:
cellList_k.append(cell_k)
for cell_v in collist_v:
cellList_v.append(cell_v)
check = dict(zip(cellList_k,cellList_v))
num = 0
for key in check:
num += 1
#print str(key),check[key]
print '%d units in check Excel'%num
print '-'*50
return check
def readDictCheck():
#name_check = raw_input('Check Excel Name: ')
filename = (name_check).decode('cp936')
data = xlrd.open_workbook(filename + '.xls',formatting_info = True)
table = data.sheet_by_index(0)
#table = data.sheet_by_name(u'sheet1')
print table.name
cellList_k = []
cellList_v = []
ncols = table.ncols
collist_k = table.col_values(0)
collist_v = table.col_values(1)
for cell_k in collist_k:
cellList_k.append(cell_k)
for cell_v in collist_v:
cellList_v.append(cell_v)
check = dict(zip(cellList_k,cellList_v))
num = 0
for key in check:
num += 1
#print str(key),check[key]
print '%d units in check Excel'%num
print '-'*50
return check
def checkDict(check,standard):
num = 0
for k in sorted(check.keys()):
if k not in standard.keys():
num += 1
print k,check[k]
elif check[k] != standard[k]:
print k,check[k],standard[k]
num += 1
print '%d numbers records'%num
def main():
global name_check
name_check = raw_input('Check Excel Name: ')
check = readDictCheck()
name_check = raw_input('Standard Excel Name: ')
standard = readDictStandard()
time.sleep(1)
checkDict(check,standard)
if __name__ == "__main__":
main()
print '-'*50
⑵ Python的__init__問題
class Person: def __init__(self, newPersionName, age): self.name = newPersionName; self.age = age; def sayYourName(self): print 'My name is %s'%(self.name); print 'My age is %s'%(self.age); def selfAndInitDemo(): persionInstance = Person('abc','20'); persionInstance.sayYourName(); ###############################################################################if __name__=="__main__": selfAndInitDemo();
你可能混用tab和空格,或者不小心沒有對齊.
[有時需要關閉文件,重新打開就會發現格式錯誤.]
我規范了下你的代碼,完全正常,你拷貝來試試.
⑶ 求斐波那契數列前20項python
根據定義遞歸求解,我們是根據需要求得的元素一步一步倒推,直到倒推到我們已知的元素 ( 第 0 個,第 1 個 ),屬於「反向」計算,那如果「正向」計算,從已知元素遞推所求元素呢?
#遞推求解,從已知元素遞推所求元素
def Fib_recurrence(n):
# 檢查輸入
if check_input(n):
if n < 2:
return n
else:
index = 2
fib_index_pre_pre = 0
fib_index_pre = 1
fib_index = 0
while n >= index:
fib_index = fib_index_pre_pre + fib_index_pre
fib_index_pre_pre = fib_index_pre
fib_index_pre = fib_index
index += 1
return fib_index
else:
# 默認返回值
return -1
⑷ python程序全排列運行不出結果
可以使用回溯法進行全排列,代碼如下:
#coding=utf-8
a=['a','b','c','d','e','f']
defcheck(b,index,ch):
foriinb:
ifi==ch:
returnFalse
returnTrue
defenum(b,index):
ifindex==len(a):
print(b)
else:
forqina:
ifcheck(b,index,q):
b=b+q
enum(b,index+1)
b=b[0:-1]
if__name__=='__main__':
b=''
enum(b,0)
運行結果:
⑸ 求下面這段python代碼該如何理解,實在看不懂
s[4]調用__getitem__(self = s, key = 4)
s[4] = 2調用__setitem__(self = s, key = 4, value = 2)
⑹ Python的一道題以及我的代碼,求大神看看有什麼可以改進的地方
這個沒有最佳解法吧,看個人理解……
下面是我的理解:
1. 不同的策略分為不同的類,提供一個統一的介面,比如
#strategy.py
class UserRate(object):
def __init__(self, comment_per_user_min=10):
#init
def check(self, userdata):
#檢查用戶數據,超過限制即報警
class UserDupContent(object):
def __init__(self, content_send_per_user=10):
#init
def check(self, userdata):
#檢查用戶數據
2. 使用依賴注入將策略注入到檢查程序:
class Guarder(object):
def addStrategy(self, strategy):
#添加一個策略
def check(self, userdata):
#使用已經添加的策略逐個檢查
#返回檢查結果
def reload_from(self, conf):
#解析配置並創建相應對象
self.addStrategy(strategy)
@classmethod
def create(cls, conf=''):
obj = cls()
if conf:
obj.reload_from(conf)
3. 調用Guarder實例檢查
guarder=Guarder.create('antispam.ini')
def index():
if guarder.check(userdata):
pass
else:
#error
def admin_reload_guarder():
'''根據web請求運行時重載配置'''
import strategy
reload(strategy)
guarder.reload(conf)
示例配置文件:
#antispam.ini
[strategies]
inst=usercontent,userrate
[usercontent]
type=strategy.UserDupContent
init.comment_per_user_min=5
[userrate]
type=strategy.UserRate
init.content_send_per_user=5
以上能夠完成的功能如下:
1. 隔離了策略代碼,使用依賴注入的方式完成
2. 策略本身是ck typing,靈活擴充
3. 策略代碼文件strategy.py不停止伺服器熱部署
當然,配置文件可以調整格式,直接用python代碼寫都可以
⑺ 使用Python實現比較倆個文件的數據,不同的存在另一個文件里
這是我之前在excel中比較兩組不同數據的代碼,修改一下完全可以滿足你的要求。
#-*-coding:utf-8-*-
importxlrd
importxlwt
fromxlutils.import
importos,time
importoperator
path=r"E:xx"
#path=raw_input('InputPath:')
os.chdir(path)
print"CurrentWorkspace:%s"%os.getcwd()
#讀取excel工作表中數據為字典
#字典形式為:{代碼:地名}
defreadDictStandard():
#name_check=raw_input('CheckExcelName:')
filename=(name_check).decode('cp936')
data=xlrd.open_workbook(filename+'.xls',formatting_info=True)
table=data.sheet_by_index(0)
#table=data.sheet_by_name(u'di')
printtable.name
cellList_k=[]
cellList_v=[]
ncols=table.ncols
forcolinrange(0,ncols):
ifnot(col%2):
collist_k=table.col_values(col)
collist_v=table.col_values(col+1)
forcell_kincollist_k:
cellList_k.append(cell_k)
forcell_vincollist_v:
cellList_v.append(cell_v)
check=dict(zip(cellList_k,cellList_v))
num=0
forkeyincheck:
num+=1
#printstr(key),check[key]
print'%nitsincheckExcel'%num
print'-'*50
returncheck
defreadDictCheck():
#name_check=raw_input('CheckExcelName:')
filename=(name_check).decode('cp936')
data=xlrd.open_workbook(filename+'.xls',formatting_info=True)
table=data.sheet_by_index(0)
#table=data.sheet_by_name(u'sheet1')
printtable.name
cellList_k=[]
cellList_v=[]
ncols=table.ncols
collist_k=table.col_values(0)
collist_v=table.col_values(1)
forcell_kincollist_k:
cellList_k.append(cell_k)
forcell_vincollist_v:
cellList_v.append(cell_v)
check=dict(zip(cellList_k,cellList_v))
num=0
forkeyincheck:
num+=1
#printstr(key),check[key]
print'%nitsincheckExcel'%num
print'-'*50
returncheck
defcheckDict(check,standard):
num=0
forkinsorted(check.keys()):
ifknotinstandard.keys():
num+=1
printk,check[k]
elifcheck[k]!=standard[k]:
printk,check[k],standard[k]
num+=1
print'%dnumbersrecords'%num
defmain():
globalname_check
name_check=raw_input('CheckExcelName:')
check=readDictCheck()
name_check=raw_input('StandardExcelName:')
standard=readDictStandard()
time.sleep(1)
checkDict(check,standard)
if__name__=="__main__":
main()
print'-'*50
⑻ 那位python大神告訴我這個程序錯哪了
沒有縮進的看著費勁
importrandom
key=''
history=[]
defcheck(num):#檢測用戶輸入是否合法
ifnum.isdigit()andlen(num)==4andlen(set(num))==4:
returnTrue
else:
returnFalse
defrandomnum():#隨機生成4個不同數字的四位數
whileTrue:
digitstr=str(random.randint(1000,10000))
iflen(set(digitstr))==4:
break
returndigitstr
defcompare(anum,bnum):
A,B=0,0
foriinbnum:
ifiinanum:
forjinanum:
ifi==jandbnum.index(i)==anum.index(j):
A+=1
elifi==j:
B+=1
returnstr(A)+'A'+str(B)+'B'
anum=randomnum()
whilekey!='Q':
key=input(' 請輸入不重復的四個數字,Q-退出遊戲:')
ifcheck(key):
history.append('{0}-->{1}'.format(key,compare(anum,key)))
print(' HISTORY:')
fori,vinenumerate(history):
print('{0:>2}.{1}'.format(i+1,v))
ifkey==anum:
print(' 恭喜你猜對了。')
break
⑼ 求Python2完成下面圖上題的代碼怎麼寫
可以使用回溯法枚舉出符合條件的矩陣,以避免使用過多的for循環嵌套。代碼如下:
#coding=utf-8
N=3
matrix=[0,0,0,0,0,0,0,0,0]
#列印矩陣
defprintMatrix(matrix):
foriinrange(len(matrix)):
print(matrix[i],end='')
if(i+1)%N==0:
print()
#判斷矩陣是否符合要求,符合返回True,否則返回False
defisOk(matrix):
foriinrange(N):
#橫向判斷每行之和是否等於15
sum=0
forjinrange(N):
sum=sum+matrix[N*i+j]
ifsum!=15:
returnFalse
#縱向判斷每列之和是否等於15
sum=0
forjinrange(N):
sum=sum+matrix[i+j*N]
ifsum!=15:
returnFalse
#判斷兩個對角線是否等於15
if(matrix[0]+matrix[4]+matrix[8])!=15:
returnFalse
if(matrix[2]+matrix[4]+matrix[6])!=15:
returnFalse
returnTrue
#下面兩個函數是使用回溯法枚舉符合要求的矩陣
defcheck(matrix,index):
foriinrange(index):
ifmatrix[i]==matrix[index]:
returnFalse
returnTrue
defenum(matrix,index):
ifindex==len(matrix):
ifisOk(matrix):
printMatrix(matrix)
print()
else:
foriinrange(1,len(matrix)+1):
matrix[index]=i
if(check(matrix,index)):
enum(matrix,index+1)
if__name__=='__main__':
enum(matrix,0)
運行結果: