1、寫一個程序,實現 abcd * 9 = dcba ,其中 a、b、c、d 都是數字python
#!/usr/bin/env python #-*- coding:utf-8 -*- "實現:abcd * 9 = dcba" for a in xrange(1,10): for b in xrange(10): for c in xrange(10): for d in xrange(10): abcd = a * 1000 + b * 100 + c * 10 + d dcba = d * 1000 + c * 100 + b * 10 + a if abcd * 9 == dcba: print abcd else: continue
2、寫一個程序,實現九宮格,要求全部的行,列,對角線的和都爲15linux
#!/usr/bin/env python #-*- coding:utf-8 -*- 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): lines = [(x,y,z) for x in self.numbers for y in self.numbers if x!=y for z in self.numbers if x!=z and y!=z and x+y+z == 15] for line1 in lines: for line2 in lines: if set(line1) & set(line2): continue for line3 in lines: if set(line1) & set(line2) & set(line3): continue if line1[0] + line2[0] + line3[0] != 15: continue if line1[1] + line2[1] + line3[1] != 15: continue if line1[2] + line2[2] + line3[2] != 15: continue if line1[0] + line2[1] + line3[2] != 15: continue if line1[2] + line2[1] + line3[0] != 15: continue print(''' _____________ |_{0}_|_{1}_|_{2}_| |_{3}_|_{4}_|_{5}_| |_{6}_|_{7}_|_{8}_| '''.format(line1[0], line1[1], line1[2], line2[0], line2[1], line2[2], line3[0], line3[1], line3[2],)) def main(): ninePaper = NinePaper() ninePaper.run() if __name__ == '__main__': main()
3、寫一個程序,根據 UID 對 /etc/passwd 進行排序app
#!/usr/bin/env python #-*- coding:utf-8 -*- import os import codecs 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()