python课的小程序~ subclass子类

Question-1:
题目描述:创建一个银行帐户的类模型,表示银行的所有客户。所有的客户都能在他们的银行帐户中存钱、取钱。任务主要如下:
创建 Account类,作为基类。Account类应该包含帐户余额,并提供构造函数;向账户中余额加钱的方法;减少账户中余额的方法;获取当前账户余额的方法。
创建 Account类的派生类:储蓄账户SavingAccount类,除去基类Account的所有功能外,储蓄账户还应该具有新的特性。储蓄账户应该提供一个计算利息的成员函数和将利息加到账户余额上的操作。
创建 Account类的派生类:支票账户CheckingAccount类,与储蓄账户不同的是,它没有利率的计算,但是他会在每笔交易后收取一定的交易费用。它需要重新定义基类Account类中的成员函数,当每笔交易完成时,在账户余额中减去交易金额。
提示:在提供上述方法时应注意出错情况的处理,比如账户余额不足的情况。

需补充代码——template.py

类的继承和多态机制

参考结果:
lab4example

Answer-1:
bank_account.py

# 2014.1.12 by Alex YU

class Account:

	def __init__(self, name):
		self.name = name
		self.balance = 0
	def deposit(self, count):
		self.balance += count
	def withdraw(self, count):
		if self.balance < count:
			return False
		else:
			self.balance -=count
			return True
	def get_balance(self):
		return self.balance

# Here are subclasses
class SavingAccount(Account):
	
	def __init__(self, name, interest_rate):
		Account.__init__(self,name)
		self.interest_rate = interest_rate
	def get_rate_of_interest(self):
		return self.interest_rate
	def get_interest(self):
		return self.interest_rate*self.balance
	def add_interest(self):
		self.balance *= (1+self.interest_rate)

class CheckingAccount(Account):

	def __init__(self, name, poundage):
		Account.__init__(self,name)
		self.poundage = poundage
	def deposit(self, count):
		print 'Want to save %d'%count
		self.balance += count*(1-self.poundage)
	def withdraw(self, count):
		maxwithdraw = self.balance/(1+self.poundage)
		if count > maxwithdraw:
			return False
		else:
			self.balance -= count*(1+self.poundage)
			return True


###########################################################
#														  #
# Do not edit any code from here to the end of this file. #
#														  #
###########################################################

def test_withdraw(acnt):
	''' Test the withdraw method in class'''
	withdraw_list = [105, 101, 100, 99, 98]

	for i in withdraw_list:
		rst = acnt.withdraw(i)
		if rst:
			print 'Withdraw %d Success.\t' % i
		else:
			print 'Withdraw %d fail.\t' % i

	print '\n'
	return

def test_Account(money):
	''' Test the Account class'''
	print ' **********  Test Account ********* '

	acnt = Account('leaf')

	print 'Before deposit, balance: %.02lf' % acnt.get_balance()
	acnt.deposit(money)
	print 'After deposit, balance: %.02lf' % acnt.get_balance()

	test_withdraw(acnt)

	return 

def test_SavingAccount(money, rate_of_interest):
	''' Test SavingAccount class'''
	print ' **********  Test SavingAccount ********* '

	saving_acnt = SavingAccount('lotus', rate_of_interest)

	print 'Before deposit, balance: %.02lf' % saving_acnt.get_balance()
	saving_acnt.deposit(money)
	print 'After deposit, balance: %.02lf' % saving_acnt.get_balance()

	print 'The rate of interest is %.02lf' % saving_acnt.get_rate_of_interest()
	print 'The interest is %.02lf' % saving_acnt.get_interest()

	draw_money = money * (rate_of_interest + 1)
	draw_rst = saving_acnt.withdraw(draw_money)
	print 'Withdraw %d' % draw_money,
	if draw_rst:
		print 'Success.'
	else:
		print 'Fail.'

	saving_acnt.add_interest()

	print 'After adding interest, the balance is %.02lf' % \
	saving_acnt.get_balance()

	test_withdraw(saving_acnt)

	return 

def test_CheckingAccount(money, rate_of_poundage):
	''' Test CheckingAccount class'''
	print ' **********  Test CheckingAccount ********* '

	checking_acnt = CheckingAccount('pepper', rate_of_poundage)

	print 'Before deposit, balance: %.02lf' % checking_acnt.get_balance()
	checking_acnt.deposit(money)
	print 'After deposit, balance: %.02lf' % checking_acnt.get_balance()
		
	test_withdraw(checking_acnt)

	return 

def test():
	money = 100
	rate_of_interest = 0.05
	rate_of_poundage = 0.01

	test_Account(money)
	test_SavingAccount(money, rate_of_interest)
	test_CheckingAccount(money, rate_of_poundage)

	return 

if __name__ == "__main__":
	test()

python课的小程序~ Queue队列

Question-1:
输入若干字符串,并按输入顺序输出。要求以队列的数据结构方式实现。
参见————堆栈

def push(stack,x):
    stack.append(x)

def pop(stack):
    return stack.pop()

def isEmpty(stack):
    return (stack == [])

def main():
    stack = []
    print "Pushing..."
    x = raw_input("Enter a string: ")
    while x != "":
        push(stack,x)
        x = raw_input("Enter a string: ")
    print "Popping..."
    while not isEmpty(stack):
        print pop(stack),

main()

 

Answer-1:

# 2013.12.31 by Alex YU

def enqueue(queue,x):
	queue.append(x)

def dequeue(queue):
	return queue.pop(0) # pop(0)!!

def main():
	queue =[]
	print 'Enqueueing...'
	x = raw_input('Enter a string: ')
	while x != '':
		enqueue(queue,x)
		x = raw_input('Enter a string: ')
	print '\nDequeueing...'
	for i in range (len(queue)): # need not 'k=len(queue)' 
		print dequeue(queue),

main()

Python Lab 11.15 ~

Question-1:
光棍的悲伤:光棍们对1总是那么敏感,因此每年的11.11被戏称为光棍节。让我们勇敢面对光棍的身份吧,现在就证明自己:给你一个整数a,数出a在二进制表示下1的个数,并输出。
Question-2:
马赛克:As an old saying goes,”马赛克是阻碍人类进步的阶梯”,python就是创造这个阶梯的作案工具之一,现在你需要利用这个作案工具,为指定图片的相应区域打上马赛克。
Question-3:
奇怪的马赛克(附加题):通常意义下,马赛克是由若干个小正方形组成的,如果你能把马赛克变成一个三角形、圆或者其他的比较复杂的几何形状,让艺术的魅力充斥其中,并获得他人的认可,将会获得额外的加分。

Answer-1:
由于bin不能用,在这里我直接做了一个转2进制的代码..

# 2013.11.15 by Alex YU

def divide(x):
        result = ''
        x = int(x)
        while x &gt; 0:
                mod = x % 2
                x /= 2
                result = str(mod) + result
        return result

def main():
	a = input('Num = ')
	print divide(a).count('1')

main()
#
# 2013.11.15 by Alex YU
#  can't be used here.. cos it's to easy
print bin(4).count('1')
#

Answer-2:
详见我的另一篇blog——《PIL mosaic 传说中的打码~

Answer-3:
这是附加题,打码的代码,我做了一个根据区域灰度匹配不同颜色阶梯的透明边小方块(其实就是预设好的小图片将原图拼出来)的代码
又忘了专业术语了,forgive me..略高端的样子 ~ ~
这里略不智能因为只能匹配20×20 pixel的方块,而且这里只取了8个等级的渐变色,whatever,程序的核心有了就行
当然网上很多骰子作画,符号作画,图片作画等等其实都差不多~

方块——blocks

# 2013.11.15 by Alex YU
# map the picture!

import Image
im = Image.open('/home/tro/b.jpg')
(pic_w,pic_h) = im.size

def divide(w,h,s):
	boxes = [(x,y,x+s,y+s) for x in range(0,w,s) for y in range(0,h,s)]
	for box in boxes:
		snip = im.crop(box)
		yield snip,box

def avg_clr(p):
	c = list(p.getdata())
	q = sum(c)/len(c)
	return q

def main():
	for a in divide(pic_w,pic_h,20):
		snip,box = a
		for grey in range(0,256,32):
			if grey&lt;=avg_clr(snip.convert('L'))&lt;grey+32:
				x = '/home/tro/pp/p'+str(grey/32)+'.png'
				xx = Image.open(x)
				im.paste(xx,box)

	im.show()
#	im.save('/home/tro/output.png')

main()
#
输入图片,,如若侵权contact me!
输入图片,<”RGB”,JPEG,3200×2000>,如若侵权contact me!
输出图片20×20点阵,
输出图片20×20点阵,<”RGB”,PNG>

Ps:
1. 待解决问题,本来是有透明边的PNG,结果处理完了之后的PNG居然直接变白色了,这里需要google,估计是PIL Image的问题(是不是不是”RGBA”所以…)
2. 上面输出图片已经是”RGBA”文件了,颜色方块之间是透明的喔

Aha,搞掂,果然是Alpha channel的问题,so这里要新合成一个图片咯,改进代码如下

# 2013.11.22 by Alex YU

import Image
im = Image.open('/home/tro/b1.jpg')
(pic_w,pic_h) = im.size
oput = Image.new('RGBA',im.size)

def divide(w,h,s):
	boxes = [(x,y,x+s,y+s) for x in range(0,w,s) for y in range(0,h,s)]
	for box in boxes:
		snip = im.crop(box)
		yield snip,box

def avg_clr(p):
	c = list(p.getdata())
	q = sum(c)/len(c)
	return q

def main():
	for a in divide(pic_w,pic_h,20):
		snip,box = a
		for grey in range(0,256,32):
			if grey&lt;=avg_clr(snip.convert('L'))&lt;grey+32:
				path = '/home/tro/pp/p'+str(grey/32)+'.png'
				block = Image.open(path)
				oput.paste(block,box,block)

#	print oput.mode		
#	oput.show()
	oput.save('/home/tro/output.png')

main()
#

python课的小程序~ 处理Excel文档

Question-1:
Excel处理:处理一个开支列表的excel文件,找出关于“Book”开支的所有条目,打印在屏幕上,并给出所有条目的总金额。
Excel文档:demo.xls

Answer-1:
Easy!
不过这只是简单用法,以后再玩高级的

# 2013.11.15 by Alex YU

import xlrd
try:
	xls = xlrd.open_workbook('demo.xls')	
	sheet = xls.sheets()[0]
	rows = sheet.nrows
	a = {}
	total = 0.0
	for i in range(1,rows):
		if sheet.cell(i,1).value == 'Book':
			for k in (0,2,3):
				a[k] = sheet.cell(i,k).value
			total = total + a[3]
			print '%s, %d, %d' % (a[0],a[2],a[3])
	print '\nTotal amount: %d' % total
except:
	print 'Oops!'
#

python课的小程序~ 统计单词、元辅音个数

Question-1:
文本处理:统计一句话中的元音,辅音,以及单词(以空格区分)个数。忽略元音和辅音的特殊情况,如”h”, “y”等,均作为辅音计算。

Answer-1:
Easy! 不过要考虑到空格的存在哟~
当然现在版本好弱,只有统计连续的一行,不能回车

# 2013.11.14 by Alex YU

# words
a = raw_input('Say sth.\n')
b = a.split(' ')# here we should consider 'Space'
w_num = len(b)-b.count('')

# vowels
v_words = 'aeiouAEIOU'
v_num = sum (a.count(i)for i in list(v_words))

# consonants
alpha_num = sum(t.isalpha()for t in a)
c_num = alpha_num-v_num

print 'word %d\nvowel %d\nconsonant %d' % (w_num,v_num,c_num)
#

PIL mosaic 传说中的打码~

新的代码~欢呼

还是homework..这次有点挑战咯
先是各种search,搞掂了ubuntu x64的PIL1.1.7(具体看我另一篇文章)
然后下载pil handbook,自学,不断改进,现在这个版本只是还算靠谱的版本吧..

题目:给个图片,给个矩阵密度,像素化(要求是按小矩形的左上第一个点颜色)
我的版本直接平均了整个色块(抱歉不懂专业术语..)(高端吧!)

# 2013.11.11 by Alex YU
# Aha! still single~
# the alpha layer of the picture can't be ignored!
# (here ignored!)
# Notice: JPEG is a greatly inaccurate format!
# for better experience Do Not Use JPEG (PNG is better~)

import Image
#1 import ImageChops
im = Image.open("/home/tro/test.jpg")
pic_w = im.size[0]
pic_h = im.size[1]
layer = im.split()

def divide(w,h,s):
	boxs = [(x,y,x+s,y+s) for x in range(0,w,s) for y in range(0,h,s)]
	for box in boxs:
		snip = layer[i].crop(box)
		yield snip,box

def avg_clr(p):
	c = list(p.getdata())
	return sum(c)/len(c)

def main():
	global i
	for i in range(3):
		for a in divide(pic_w,pic_h,1):# u can change num
			snip,box = a
			layer[i].paste(avg_clr(snip),box)

	output = Image.merge("RGB",layer)
	output.save("/home/tro/output.png")
#1	dif = ImageChops.difference(im,output)
#1	dif.show()
main()
#
输入图片,,如若侵权contact me!
输入图片,<“RGB”,JPEG,620×340>,如若侵权contact me!
输出图片,
输出图片10×10,<“RGB”,PNG>
输出图片,
输出图片20×20,<“RGB”,PNG>
# 2013.11.12 by Alex YU
# process three bands at one step!

import Image
im = Image.open("/home/tro/b.jpg")

def avg_clr(p):
	c = list(p.getdata())
	b = len(c)
	k = map(sum,zip(*c))# greatest step!
	q = (k[0]/b,k[1]/b,k[2]/b)# need perfected!
	return q

def divide(w,h,s):
	global im
	boxes = [(x,y,x+s,y+s) for x in range(0,w,s) for y in range(0,h,s)]
	for box in boxes:
		snip = im.crop(box)
		im.paste(avg_clr(snip),box)

def main():
	divide(im.size[0],im.size[1],20)# u can change num
	im.show()
#	im.save("/home/tro/output.png")

main()
#
# 2013.11.12 by Alex YU
# process three bands at one step!

import Image
im = Image.open("/home/tro/b.jpg")
(pic_w,pic_h) = im.size

def divide(w,h,s):
	boxes = [(x,y,x+s,y+s) for x in range(0,w,s) for y in range(0,h,s)]
	for box in boxes:
		snip = im.crop(box)
		yield snip,box

def avg_clr(p):
	c = list(p.getdata())
	b = len(c)
	k = map(sum,zip(*c))# greatest step!
	q = (k[0]/b,k[1]/b,k[2]/b)# need perfected!
	return q

def main():
	for a in divide(pic_w,pic_h,20):# u can change num
		snip,box = a
		im.paste(avg_clr(snip),box)
	im.show()
#	im.save("/home/tro/output.png")

main()
#

Ps:
1. #1 是为了测试通道处理的图像(矩形设置为1×1)与原图的差异从而判断图像处理部分代码是否正确
2. 这里暂时使用长宽的公约数,未来可能改个补一个边界的代码
3. 第二个代码和第三个代码同时处理RGB三通道,速度比原始代码快了近一倍,第二个代码在测试平均下来比第三个代码快0.x秒
4. 这里环境是虚拟ubuntu13.04 python2.7 PIL1.1.7

References:
Python PIL 骰子作画的算法 其实是打码 – http://www.douban.com/note/186940605/
骰子作画的算法 python – http://fayaa.com/code/view/24264/
PIL-handbook.pdf

python课的小程序~ 乘法口诀表

这应该算是真正意义上的第一个python程序了吧,还是完成作业
作业就是打印个乘法口诀表,真心比较难搞(以后再看这句话估计要笑了)

Question

# 2013.11.01 by Alex YU
# Three parts: assignment b[] & a[] & print
# Notice: the len should be fixed. by using .ljust(6) ~~~~

# assignment b[]~
b = []
i = 0
j = 0
r = 1
s = 0
while j < 9:
     i = 0
     s = 0
     while i < 10 - r:
          b.append(str(r) + 'x' + str(r+s) + '=' + str(r*(r+s)))
          s = s + 1
          i = i + 1
     r = r + 1
     j = j + 1

a = [['' for x in range(9)]for y in range(9)]
i = 0
j = 0
k = 0
while j < 9:
     i = j
     while i < 9:
          a[i][j] = b[k]
          k = k + 1
          i = i + 1
     j = j + 1

for i in a:
     for j in i:
          print  j.ljust(6),
     print
#

已经笑了!,研究了好久之后终于诞生了Beta Ver.


# 2013.11.13 by Alex YU
# Beta Ver.

for i in range(1,10):
    for j in range(1, i+1):
        print "%dx%d=%-2d"%(j,i,i*j),# "%-2d"!!!
    print
#

又笑了!


# 2013.11.13 by Alex YU
# beyond

print ("\n".join("".join("%dx%d=%-3d" % (j,i,i*j) for j in  range(1,i+1))for i in range(1,10)))
#