很抱歉,如果已用其他方式或在其他地方回答了该问题,我只是想不通。因此,我第一次玩python,只是试图创建一个非常简单的基本区块链模型,在其中可以向链中添加值,但是当我添加值时,我会在列表中显示总的可用“资金”。 / p>
这是我到目前为止所拥有的:
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)
基本上,请考虑一下这是一个简单的钱包,每次向其中添加资金时,您都会在其中使用可用资金。它还将跟踪每次添加或扣除钱款的情况。正如上面提到的,一个非常基本的区块链。
对此,我将不胜感激。
答案 0 :(得分:1)
使用功能中带有默认值的列表会使您失望:"Least Astonishment" and the Mutable Default Argument
将数据分组在一起最好将其分组-f.e.作为不可替代的元组。我会将您的区块链存储为(last_balace, new_op)
的元组,并添加一些检查,以确定该链在插入时是否有效。
您当前的方法将需要对列表进行切片以获取所有“旧值”和所有“新值”,或者每2个元素对其进行分块并在这些切片上进行操作-使用元组更加清楚。
如果您想继续使用平面列表并为解决方案使用块/切片,请参见Understanding slice notation和How do you split a list into evenly sized chunks?。
将元组列表用作链的示例:
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.