⑴ 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)
运行结果: