首页 > 解决方案 > 在添加单个值时在列表中添加总值

问题描述

对不起,如果这已经以其他方式或地方得到了回答,我就是想不通。所以我第一次玩python,只是想创建一个非常简单的基本区块链模型,我可以在其中向链添加值,但是当我添加值时,我会在列表中显示可用的总“资金”。

这是我到目前为止所拥有的:

import numpy as np

name = raw_input("please enter your name: ")

# For some reason I have to use the raw_input here or get an error message
original_money = float(input("how much money do you have? "))

# Requesting user to input their original available "funds" amount
print("Hi " + name + " you have $" + str(original_money))

print("in order to make purchases, you need to add money to your wallet")
wallet = [original_money]

def get_last_wallet_value():
    return wallet [-1]

def add_value(last_added_value, existing_value=[original_money]):
    wallet.append([existing_value, last_added_value])

# I am lost here, no idea what to do to add the whole value of available "funds" within the list as they are getting added to the list
def sum_wallet_content():
    return np.sum(wallet)  

tx_value = float(input("please enter how much you would like to add: "))
add_value(tx_value)
print(name + " you now have $" + str(tx_value+original_money) + " in your        acount!")

# Here is where my problem starts since it is calling the sum_wallet_content and I am having troubles setting that up

tx_value = float(input("please enter how much you would like to add: "))
add_value(tx_value, get_last_wallet_value())
print(name + " you now have $" + sum_wallet_content() + " in your account!")

tx_value = float(input("please enter how much you would like to add: "))
add_value(tx_value, get_last_wallet_value())

tx_value = float(input("please enter how much you would like to add: "))
add_value(tx_value, get_last_wallet_value())

tx_value = float(input("please enter how much you would like to add: ")) 
add_value(tx_value, get_last_wallet_value())

print(wallet)

基本上,认为这是一个简单的钱包,每次向其中添加资金时,您都会在钱包中获得可用资金。它还将跟踪每次添加或扣除资金的时间。如前所述,一个非常基本的区块链。

我将不胜感激对此的任何建议。

标签: pythonpython-3.xlistarraylist

解决方案


在函数中使用带有默认值的列表会让你大吃一惊:“Least Astonishment”和可变默认参数


将数据存储在属于一起的平面列表中最好通过将其分组来完成 - fe 作为不可变元组。我会将您的区块链存储为元组,(last_balace, new_op)并添加一些检查链在插入时是否有效。

您当前的方法需要您对列表进行切片以获取所有“旧值”和所有“新值”,或者每 2 个元素对其进行分块并对这些切片进行操作 - 使用元组更清楚。

请参阅了解切片表示法如何将列表拆分为大小均匀的块?如果您想继续使用平面列表并为您的解决方案使用块/切片。


使用元组列表作为链的示例

def modify(chain,money):
    """Allows modification of a blockchain given as list of tuples:
       [(old_value,new_op),...]. A chain is valid if the sum of all
       new_op is the same as the sum of the last chains tuple."""
    def value():
        """Calculates the actual value of a valid chain."""
        return sum(chain[-1])
    def validate():
        """Validates chain. Raises error if invalid."""
        if not chain:
            return True
        inout = sum(c[1] for c in chain) # sum single values
        last = value()
        if inout == last:
            return True
        else:
            raise ValueError(
            "Sum of single positions {} does not match last chain element {} sum.".format(
            inout,last))

    # TODO: handle debt - this chain has unlimited credit

    if chain is None:
        raise ValueError("No chain provided")
    elif not chain:    # empty chain: []
        chain.append( (0,money) )
    elif validate():   # raises error if not valid
        chain.append( (value(),money))
    print(chain,value())

用法:

modify(None,42)   # ValueError: No chain provided

block = []
modify(block,30)    # ([(0, 30)], 30)
modify(block,30)    # ([(0, 30), (30, 30)], 60)
modify(block,-18)   # ([(0, 30), (30, 30), (60, -18)], 42)

# fraudulent usage
block = [(0,1000),(1040,20)]
modify(block,10) 
# => ValueError: Sum of single positions 1020 does not match last chain element 1060 sum.

推荐阅读