zoukankan      html  css  js  c++  java
  • Show me the code练习题

    网址 https://github.com/Show-Me-the-Code/show-me-the-code

    初学python拿来练手非常不错。

    1、

    第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 类似于图中效果

    头像

     1 # -*- coding:utf-8 -*-
     2 import sys
     3 import glob, os
     4 from PIL import Image, ImageDraw, ImageFont
     5 
     6 type = sys.getfilesystemencoding()
     7 
     8 font = ImageFont.truetype("msyhbd.ttc", 30)
     9 
    10 for infile in glob.glob("*.jpg"):
    11     file, ext = os.path.splitext(infile)
    12     im = Image.open(infile)
    13     w, h = im.size
    14     x=w*0.8
    15     y=h*0.1
    16     drawSurface = ImageDraw.Draw(im)
    17     drawSurface.text((x,y), "4", fill=(255,0,0), font=font)
    18     im.show()
    View Code

    第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?

    主键+随机码的方式.

    这种方法优点:使用也比较简单,不用直接去查询数据库,而最大的优点是查询的时候,可以根据邀请码直接得到主键id, 然后根据id去数据库查询(速度很快),再比较查询出来的邀请码和用户提交的邀请码是否一致。

    1. 生成:id(数据库primary key )->16进制 + "L(标识符)" +随机码
    2. 获取id:获取16进制的id再转回10进制
     1 # coding:utf-8
     2 import random
     3 import string
     4 
     5 def created_code(id, length=10):
     6     id_ = hex(id)    # 将10进制整数转换成16进制,以字符串形式表示
     7     id_ = id_[2:]+'L'
     8     length = length-len(id_)
     9     chars = string.ascii_letters+string.digits
    10     code = id_+''.join([random.choice(chars) for i in range(length)])
    11     return code
    12     
    13 def get_Id(code):
    14 id_ = code.split('L')[0]
    15 id = int(id_, 16)
    16 return str(id)
    17 
    18 
    19 if __name__=='__main__':
    20     for i in range(0,200):
    21     code = create_code(i)
    22     id = get_Id(code)
    23     print code, id
    24     
    25     
    View Code

    第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。

     1 # coding:utf-8
     2 from uuid import uuid4
     3 import MySQLdb, random, string
     4 
     5 chars = string.digits + sting.letters
     6 
     7 def uuidkey(num):  # 使用uuid方法得到随机值
     8     id_list = [str(uuid4()) for i in range(num)]
     9     return id_list
    10     
    11 def randomkey(num):  #使用random随机取得数据
    12     id_list = ["".join(random.sample(chars, 20)) for i in range(num)]
    13     return id_list
    14     
    15 def create_table_put_keys(id_list, table):  # 将获得的随机值存入mysql
    16     conn = MySQLdb.connect(
    17         host='localhost',
    18         port=3306,
    19         user = 'root',
    20         passwd = 'xxxx',
    21         db = 'test',)
    22         
    23     cur = conn.cursor()
    24     cur.execute("drop table if exists %s" %table)   # 若存在table类则删除
    25     cur.execute("create table %s(id int, coupon char(40))" %table)   #创建数据表
    26     tem = 1
    27     for i in id_list:  # 将id_list里面的数据插入到mysql中
    28         cur.execute("insert into %s values('%d', '%s')" %(table, temp, i))
    29         temp = temp+1
    30         
    31     cur.close 
    32     conn.commit() # 提交数据
    33     conn.close()
    34     
    35     
    36 def main():
    37     create_table_put_keys(uuidkey(200), 'uuidtable')
    38     create_table_put_keys(randomkey(200), 'randomkey')
    39     
    40 if __name__=='__main__':
    41     main()
    View Code

    第 0003 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。

    第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。

     出处:https://www.jianshu.com/p/eaaa33d14794

     1 # coding=utf-8
     2 import re
     3 from collections import Counter
     4 
     5 def cal(filename='ddddd.txt'):
     6     with open(filename, 'r') as f:
     7         data = f.read()
     8         data = data.lower()
     9         # 替换除了n't这类连字符外的所有非单词字符和数字字符
    10         datalist = re.split(r'[s
    ]+', data)
    11         return Counter(datalist).most_common()
    12         
    13 if __name__ == '__main__':
    14     dic = cal()
    15     for i in range(len(dic)):
    16         print('%15s  ---->   %3s' % (dic[i][0],dic[i][1]))
    View Code

    第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。

    图片分辨率处理

     1 import os
     2 from PIL import Image
     3 
     4 pathDir='F:CloudMusic'
     5 os.chdir(pathDir)
     6 
     7 def get_imagelist():  # 获取照片名称list
     8     img_list = []
     9     list_dir = os.listdir(pathDir)
    10     for x in list_dir:
    11         if '.jpg' in x:
    12             img_list.append(x)
    13         else:
    14             print("This is not a picture:" +x)
    15     return img_list
    16     
    17 def modify_imgsize():
    18     for filename in get_imglist():
    19         img=Image.open(filename)
    20         if max(img.size)>1136:
    21             value=max(img.size)/1136.0
    22             newsize = (int(img.size[0]/value), int(img.size[1]/value))
    23             newimg = img.resize(newsize, Image.ANTIALTAS)  #修改大小
    24             newimg.save('new_'+filename)
    25         else:
    26             print("This picture is available:" +filename)
    27             
    28             
    29 if __name == '__main__':
    30     modify_imgsize()
    View Code

     第 0006 题:使用 Python 生成类似于下图中的字母验证码图片

    我们用随机颜色填充背景,再画上文字,最后对图像进行模糊:

     1 # coding:utf-8
     2 
     3 from PIL import Image, ImageDraw, ImageFont, ImageFilter
     4 import random
     5 
     6 # 随机字母
     7 def rndChar():
     8     return chr(random.randint(65, 90))
     9     
    10 # 随机颜色1
    11 def rndColor():
    12     return (random.randint(64, 255), random.randint(64,255),  random.randint(64,255))
    13     
    14 # 随机颜色2
    15 def rndColor2():
    16     return (random.randint(32,127), random.randint(32,127), random.randint(32, 127))
    17 
    18 def compose():
    19     width = 240
    20     height = 60
    21     image = Image.new('RGB', (width,height), (255,255,255))
    22     # 创建font对象
    23     font = ImageFont.truetype('C:/windows/fonts/Arial.ttf',36)
    24     # 创建Draw对象
    25     draw = ImageDraw.Draw(image)
    26     # 填充每个像素
    27     for x in range(width):
    28         for y in range(height):
    29             draw.point((x,y), fill=rndColor())
    30             
    31     # 输出文字
    32     letters = []
    33     for t in range(4):
    34         letters.append(rndChar())
    35         draw.text((60 * t+10, 10), letters[t], font=font, fill=rndColor2())
    36     # 模糊
    37     image.save('code.jpg', 'jpeg')
    38     image = image.filter(ImageFilter.BLUR)
    39     image.save('filter.jpg', 'jpeg')
    40     print (letters)
    41 
    42 compose()
    View Code

    第 0007 题:Python敏感词检测

     1 # coding:utf-8
     2 import cmd
     3 # 存放敏感词文件的路径
     4 filtered_words_filepath = 'D:/filtered_words.txt'
     5 class CLI(cmd.Cmd):
     6     def __init__(self):
     7         cmd.Cmd.__init__(self) # 初始化,提取敏感词列表
     8         self.intro = 'Python敏感词检测:' # 输出欢迎信息
     9         f = open(filtered_words_filepath)
    10         self.words = list(map(lambda i:i.strip('
    '), f.readlines()))
    11         self.prompt = ">>>" # 定义提示符
    12         
    13     def default(self, line):
    14         if any([i in line for i in self.words]):
    15             print ('Freedom')
    16         else:
    17             print ('Human Rights')
    18             
    19     def do_quit(self, arg):
    20         exit()
    21         return True
    22         
    23         
    24 if __name__ == '__main__':
    25     cli = CLI()
    26     cli.cmdloop()
    View Code
  • 相关阅读:
    AtCoder Regular Contest 093
    AtCoder Regular Contest 094
    G. Gangsters in Central City
    HGOI 20190711 题解
    HGOI20190710 题解
    HGOI 20190709 题解
    HGOI 20190708 题解
    HGOI20190707 题解
    HGOI20190706 题解
    HGOI 20190705 题解
  • 原文地址:https://www.cnblogs.com/zijue/p/10065102.html
Copyright © 2011-2022 走看看