One Py Per Day

偶然看到Python 练习册,每天一个小程序,感觉挺适合Python初学者。
这个Project有26个小Project,通过完成每个小Project应该可以学习到Python开发中比较常用的一些库。所以打算将这个作为Python练习,并将笔记写到blog上分享。


Project 000

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

One Py Per Day_第1张图片
头像

思路:找到一个可以处理图像的库,然后读入图片,将字画到图片中。

Google一下,PIL满足处理图片的要求,不过该库已经停止维护。Pillow是PIL的一个fork,目前有继续更新维护,直接install该库就可以使用PIL的功能。

在Pillow的Handbook中有PIL基本的操作介绍,更详细的功能需要参考API.

from PIL import Image, ImageFont, ImageDrawimage

# Read image from file and convert it to 'RGBA' mode.
avatar = Image.open("/filepath/avatar.jpg").convert('RGBA')

# Get a font style from 'ttf' file, and set the font size. 
# We can also specify ImageFont.load_default() as the font style, 
# but that mean we can't specify the font size because 
# the default font-style is bitmap font style.
font = ImageFont.truetype("/Library/Fonts/Roboto-Regular.ttf", 64)

# Set text and get text bounds.
text = "Hello World"
text_bounds = font.getsize(text)

# Set the avatar image to ImageDraw to allow it draw text on the image.
draw = ImageDraw.Draw(avatar, 'RGBA')

# Draw the text to specify region, the attribute 'fill' mean the 'RGBA' for text.
draw.text((image.size[0] - text_bounds[0], 0), text = text, font = font, fill = (255, 0, 0, 128))

# Show the image.
avatar.show()

Project 001

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

思路:随机生成200个长度为n的不同的字符串。可以限定字符串紧由大写字母组成。random可以生成随机数,string可以提供大写字母,set可以用来判断新生成的字符串是否已经存在。

import string
import random
import sys


def generate_random_string_with_length(n):
    return ''.join(random.choice(string.ascii_uppercase) for _ in range(n))

n = int(sys.stdin.readline())
coupons = set()
while len(coupons) < 200:
    new_coupon = generate_random_string_with_length(n)
    if new_coupon not in coupons:
        coupons.add(new_coupon)

for coupon in coupons:
    print coupon


你可能感兴趣的:(One Py Per Day)