Python AA消费算账程序

写了python程序,计算多个人一起消费后,每个人应该支出或回收的费用。只需要按照程序提示,输入每个人消费的表达式,程序自动计算总开销、每人平均消费,输出总帐(负数为需要支出的,整数为需要回收的费用)。程序也支持从detail.txt文件解析开支数目。

import sys, re, commands

cost = {}

if len(sys.argv) > 1:
    f = file(sys.argv[1])
    sum = 0
    head = True
    for line in f.readlines():
        if head:
            name = line.strip()
        if line == 'n':
            head = True
            print 'n', name, sum
            cost[name] = sum
            sum = 0
            continue
        if not head:
            num = float(re.findall("d+.*d*", line)[-1])
            print '+', num,
            sum += num
        head = False

    print 'n', name, sum
    cost[name] = sum
    f.close()
else:
    name_list = ['kong', 'lei', 'yong', 'cao']

    for name in name_list:
        cost[name] = float(commands.getoutput(
        'echo "scale=2;%s" | bc' % raw_input("%s:t" % name)))
        print "t=", cost[name]

print cost
print

sum = 0
for i in cost.values():
    sum += i
avg = float(sum) / len(cost)

for name,num in cost.items():
    print name, 't', '%.2f' % (num - avg)
[amos@amosk ~]$ python m.py
kong:	20+20+200+7+660+154
	= 1061.0
lei:	69+25+32+35.7+70+70+171.5+300
	= 773.2
yong:	214+77
	= 291.0
cao:	10
	= 10.0
{'lei': 773.2, 'cao': 10.0, 'yong': 291.0, 'kong': 1061.0}

lei 	239.40
cao 	-523.80
yong 	-242.80
kong 	527.20
[amos@amosk ~]$ python m2.py detail.txt
+ 20.0 + 20.0 + 200.0 + 7.0 + 660.0 + 154.0 
kong: 1061.0
+ 214.0 + 77.0 
yong: 291.0
+ 69.0 + 25.0 + 32.0 + 35.7 + 70.0 + 70.0 + 171.5 + 300.0 
lei: 773.2
+ 10.0 
cao: 10.0
{'lei:': 773.2, 'cao:': 10.0, 'yong:': 291.0, 'kong:': 1061.0}

lei: 	239.40
cao: 	-523.80
yong: 	-242.80
kong: 	527.20

detail.txt

kong:
香油芥末20
醋鸡蛋20
电费 200
纸杯 7
网费 660
洗衣液 154

yong:
天然气:214
米:77

lei:
架子:69
纸: 25
洗衣液+龙头: 32
油,洗洁精 35.7
灯 70
洗衣液,纸 70
超市:171.5
电费 300

cao:
菜10

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.