Python block chain simple bookkeeping implementation

Source: Internet
Author: User

The basics of block chains are described in the previous Python block chain primer, and the structure of block and block chains is implemented in Python. In this article, we will implement a simple bookkeeping function based on the above content.

The functions of bookkeeping are as follows: to achieve basic income and expenditure records, calculate current balances, and make a simple statistical analysis of income and expenditure.

Billing records are formatted as follows:

Date | description | amount

Here's a step-by-step implementation of these features. I. Definition of income and expenditure records

In the previous section, the content of the block is a simple text, where implementation will be based on blocks to implement a support record format class, the code is as follows:

In [36]:

From datetime import DateTime

class Accountbill (block):
    
    def __init__ (self, Content, amount):
        t = DateTime.Now (). Strftime ('%y-%m-%d%h:%m:%s ')
        data = "{}|{}| {} '. Format (t, content, amount) return
        super (Accountbill, self). __init__ (data)
    
    '
        get amount of quantity
    ' def get_amount (self):
        amount = 0
        if self.data:
            amount = Int (self.data.split (' | ') [2])
        Return amount
    
    def get_content (self):
        content = '
        if self.data:
            content = self.data.split (' | ') [1]
        Return content

    def __repr__ (self): return
        ' Bill: {}> '. Format (
            self.data
        )

In [37]:

# Create Records

Accountbill (' Test ', 100)

OUT[37]:

bill:2017-07-30 10:46:23| Test |100>
ii. Calculation of current balance

The revenue and expenditure records are defined above, and then a method is defined on the basis of blockchain to calculate the current balance. The code is as follows:

In [91]:

From collections import Ordereddict

class Accountbook (Blockchain):
    
    def __init__ (self):
        Self.head = None   # Point to the newest block
        self.blocks = ordereddict ()   # contains a dictionary of all chunks

    '
        add Records '
    def add_block (self, New_bill):
        new_bill.mine ()
        super (Accountbook, self). Add_block (New_bill)
        
    '
        calculate current balance
    '
    def balance (self):
        balance = 0
        if self.blocks:
            for K, V in Self.blocks.items ():
                balance + = v[' Block '].get_amount () return
        balance

    
    def __repr__ (self):
        num_existing_blocks = Len (self.blocks) Return
        ' accountbook<{} Bills, head: {}> '. Format (
            num_existing_blocks,
            self.head.identifier if Self.head Else None
        )

In [92]:

# create several records book

= Accountbook ()

B1 = Accountbill (' wages ', 10000)
Book.add_block (b1) b2

= Accountbill (' Rent ',- 2500)
Book.add_block (b2)

B3 = Accountbill (' clothes ', -1500)
Book.add_block (b3) B4

= Accountbill (' Eat ',- 1000)
book.add_block (b4)

B5 = Accountbill (' Stock income ',) Book.add_block
(B5) B6

= Accountbill (' See movie ', -200)
Book.add_block (b6)

b7 = Accountbill (' shopping ', -1000)
Book.add_block (b7) B8

= Accountbill (' Water and electricity costs, etc. ', -100
book.add_block (B8)

In [93]:

# Calculate Current balance

book.balance ()

OUT[93]:

3900
Brief analysis of income and expenditure records

In [76]:

# Print revenue record for

k,v in Book.blocks.items ():
    print (v[' block '].data)

2017-07-30 19:57:57| wage |10000
2017-07-30 19:57:57| rent |-2500
2017-07-30 19:57:57| dress |-1500
2017-07-30 19:57:58| dinner |-1000
2017-07-30 19:57:58| stock income |200
2017-07-30 19:57:58| Watch movie |-200
2017-07-30 19:57:59| shopping |-1000
2017-07-30 19:57:59| Utilities | -100

In [50]:

# showing revenue and expenditure records using a histogram

%matplotlib inline

import matplotlib
import numpy as NP
import Matplotlib.pyplot as plt< c4/>plt.rcparams[' Font.sans-serif ']=[' Simhei '] #用来正常显示中文标签


# initialize data
x_data = []  # amount
y_data = []  # Description
colors = []  # color for

k,v in Book.blocks.items ():
    bill = v[' block ']
    y_data.append (bill.get_ Content ())
    amount = Bill.get_amount ()
    If amount > 0:
        x_data.append (amount)
        colors.append (' Blue ')
    else:
        x_data.append (-amount)
        colors.append (' red ')

        
Y_pos = Np.arange (len (y_data))
 
Plt.bar (Y_pos, X_data, align= ' center ', alpha=0.5, color=colors)
plt.xticks (Y_pos, Y_data)
Plt.ylabel (' Amount ')
plt.title (' Income record ')
 
plt.show ()



In [55]:

# Simple analysis Expenditure composition

labels = []
amounts = []
colors = [' Gold ', ' yellowgreen ', ' lightcoral ', ' Lightskyblue '] # display in different colors 
  for k,v in Book.blocks.items ():
    bill = v[' blocks ']  
    amount = Bill.get_amount ()
    
    # Show only expenses
    if amount < 0:
        Labels.append (Bill.get_content ())
        amounts.append (-amount)
        

Plt.pie (amounts, labels=labels, colors= Colors, shadow=true, autopct= '%1.1f%% ')
plt.axis (' equal ')
plt.show ()
Author: Walker Python enthusiasts Community column author authorized original release, please do not reprint, thank you.

Source: Python's block chain simple bookkeeping implementation


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.