45. Python 小练习
短信预约 -IT技能 免费直播动态提醒
需求1:
ABCD * 9 = DCBA
通过计算方法,给我们计算出 A = ? B = ? C = ? D = ?
A: 1-9
B: 0-9
C: 0-9
D: 1-9
A != B != C != D
代码:
class CountNumber(object):
def __init__(self):
print("ABCD * 9 = DCBA; A != B != C != D")
def numAbcd(self):
for A in range(1, 10):
for B in range(0, 10):
for C in range(0, 10):
for D in range(1, 10):
if ( A * 1000 + B * 100 + C * 10 + D) * 9 == (D * 1000 + C * 100 + B * 10 + A):
print("{0}{1}{2}{3} * 9 = {4}{5}{6}{7}".format(A, B, C, D, D, C, B, A))
print("A = {0}, B = {1}, C = {2}, D = {3}".format(A, B, C, D))
def main():
countNumber = CountNumber()
countNumber.numAbcd()
if __name__ == '__main__':
main()
需求2:
_____________
|_A_|_B_|_C_|
|_D_|_E_|_F_|
|_G_|_H_|_I_|
A, B, C, D, E, F, G, H, I 必须是1-9数字,且不能重复
所有的行,列,对角线的和都为15
class NinePaper(object):
def __init__(self):
self.numbers = list()
for i in range(1, 10):
self.numbers.append(i)
print("numbers = {0}".format(self.numbers))
def run(self):
for A in range(1, 10):
l1 = list()
l1 += self.numbers
l1.remove(A)
for B in l1:
l2 = list()
l2 += l1
l2.remove(B)
for C in l2:
l3 = list()
l3 += l2
l3.remove(C)
for D in l3:
l4 = list()
l4 += l3
l4.remove(D)
for E in l4:
l5 = list()
l5 += l4
l5.remove(E)
for F in l5:
l6 = list()
l6 += l5
l6.remove(F)
for G in l6:
l7 = list()
l7 += l6
l7.remove(G)
for H in l7:
l8 = list()
l8 += l7
l8.remove(H)
for I in l8:
if A+B+C == D+E+F == G+H+I == A+D+G == B+E+H == C+F+I == A+E+I == C+E+G == 15:
print('''
_____________
|_{0}_|_{1}_|_{2}_|
|_{3}_|_{4}_|_{5}_|
|_{6}_|_{7}_|_{8}_|
'''.format(A, B, C, D, E, F, G, H, I))
def main():
ninePaper = NinePaper()
ninePaper.run()
if __name__ == '__main__':
main()
需求3:
将文件passwd的内容,写入新的文件并排序,新文件名为newpasswd
import codecs
import os
class SortPasswd(object):
def __init__(self):
self.passwd = "passwd"
self.newpasswd = "newpasswd"
self.contextList = list()
if not os.path.exists(self.passwd):
print("please download passwd from linux.")
exit(1)
print("sort file is :{0}".format(self.passwd))
print("sorted file is :{0}".format(self.newpasswd))
def getContextList(self):
with codecs.open("passwd") as fr:
self.contextList += sorted(fr.readlines(), key=lambda line:int(line.split(":")[2]), reverse=False)
def writeContextList(self):
with codecs.open("new_passwd", "w") as fw:
fw.writelines(self.contextList)
def main():
sortpasswd = SortPasswd()
sortpasswd.getContextList()
sortpasswd.writeContextList()
if __name__ == '__main__':
main()
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341