I am making a recursive function for retrieving outer ethereum accounts. Once I loop through the first list of accounts, I want to take the first one and show the accounts he sent money to, then go back to previous interation take second account and so on.. problem is I don't know how to make my function stick to the for loop, because current account get replaced after the iteration..Any ideas
tx = get_transactions(start_address)
def breadth_search(transactions):
if transactions:
accounts = []
for i, tran in enumerate(transactions):
print(i, tran)
if tran['tx_to'] not in accounts:
accounts.append(tran['tx_to'])
return accounts
def some_func(trans):
tx_list = breadth_search(trans)
for i, tr in enumerate(tx_list):
print(i)
breadth_search(get_transactions(tr))
for i, tr in enumerate(tx_list):
some_func(get_transactions(tr))
Related
I'm adding a function to a class to output the item with the lowest price but what I'm getting are all the prices. See photo and code. What am I missing on the code?
def get_low_price(self):
self.get_total_toys()
#To check if toybox is empty or not
if self.total > 0:
msg = f'The toy box contains {self.total} toys\n'
for a_toy in self.all_toys:
self.get_total_cost()
msg += f'A {(a_toy.colour).lower()} {a_toy.name} which cost ${a_toy.price:.2f}\n'
for i in [a_toy.price]:
i = ([i])
print(min(i))
return f'{msg}Total cost: ${self.cost_total:.2f}'
This inner loop isn't doing anything useful:
for i in [a_toy.price]:
i = ([i])
print(min(i))
Here a_toy is already just a single toy. Looping over a new list containing only its price doesn't accomplish anything you could get just by accessing a_toy.price directly, and rebinding the loop variable i to another new list (in extraneous parentheses) doesn't add anything.
I think you want to move all of the min-finding logic outside of the earlier loop, unless you want to compare prices yourself. Instead, you can use just one min call, outside of the loop:
for a_toy in self.all_toys: # don't include the stuff below in this loop
...
cheapest = min(self.all_toys, key=lambda t: t.price) # find cheapest
# do something down here with cheapest, or cheapest.name, maybe
I didn't understand what exactly you are trying to do using the for loop in that method. If you are thinking that i = ([i]) is going to append price to a list then it's wrong. Use the below logic and rewrite your method. It will work.
toys = {"doll": 5, "hulk": 10, "teddy": 15}
cheapest_toy_name = ""
cheapest_toy_price = float("inf")
for k, v in toys.items():
if cheapest_toy_price > v:
cheapest_toy_price = v
cheapest_toy_name = k
print(cheapest_toy_name)
I want to set up a recursive loop to iterate over different levels of a transaction tree until a predefined depth is reached.
Example:
A transfers funds to B and C (depth 1)
- B transfers funds to D and E (depth 2)
- C transfers funds to F and G (depth 2)
etc.
To do so, I have set up the following function:
def traverse(target, depth):
try:
print('Starting analysis of parent address {}'.format(target))
result=callAddress(target)
inner_transaction_targets=analyseTransaction(result)
traversed_addresses=compileAddresses(compiled_receiver_addresses,inner_transaction_targets) #Compile list of start addresses
if depth > 0:
for inner in inner_transaction_targets:
print('Starting analysis of child address {} at depth {}.'.format(inner,depth))
inner_transaction_targets=inner_transaction_targets.pop(0)
print(inner_transaction_targets)
return traverse(inner, depth-1)
else:
return traversed_addresses
except:
print('Could not traverse.')
The functions callAdress, analyseTransaction and compileAdresses themselves should not be relevant to this problem. However to offer a brief description:
analyseTransaction will offer a list of all receiver addresses involved in a given transaction
compileAdresses collects the scanned addresses in a master list
See here the other functions:
def callAddress(bitcoin_address): #This function serves to retrieve the JSON respose from blockchain.info
try:
r = requests.get("https://blockchain.info/address/{}?format=json".format(bitcoin_address))
unparsed=r.content
parsed = json.loads(unparsed)
return parsed
except: #unparsed.status=="400":
print ("Incorrect bitcoin address")
def compileAddresses(compiled_receiver_addresses,input_addr): #This function serves to add extracted transactions to a master list (compiled_receiver_addresses)
try:
compiled_receiver_addresses.append(input_addr)
return compiled_receiver_addresses
except:
print('Failed to compile')
def analyseTransaction(response): #This function serves to extract the wallet addresses that the specified wallet has sent funds to (transaction targets)
try:
transaction_targets=[]
wallet_transactions=response['txs']
for txs_entry in wallet_transactions:
print ("{:=^22}".format(""))
print ("Checking outgoing transaction with Hash: {}".format(txs_entry['hash']))
print ("Transaction occured at: {}".format(datetime.fromtimestamp(
int(txs_entry['time']) ).strftime('%Y-%m-%d %H:%M:%S')))
print ("{:=^22}".format(""))
for out in txs_entry['out']:
outbound_addr=out['addr']
print ("In this transaction funds were sent to this wallet: {}".format(out['addr']))
print ("Amount sent: {}".format(int(out['value']) * 10**-8))
transaction_targets.append(outbound_addr)
cleaned_transaction_targets = list(dict.fromkeys(transaction_targets))
return cleaned_transaction_targets
except:
print('Dead End')
My issue is that the recursive loop keeps getting stuck on the first value, i.e. it is looping the very first value of "inner" over and over again instead of going down the list that is inner_transaction_targets
I have tried to drop the very first value in this list by using inner_transaction_targets.pop(0) but to no effect.
How do I have to modify this function so that it does what I want?
Your code has some errors that are most likely hindering its successful completion, such as:
The return is within a loop.
The object returned is in fact a self-reference to the traverse() function.
The .pop() method is not a good practice.
I would suggest you create a separate function that will return a single object for each inner transaction, much like what compile_addresses() does.
You then add this new function into the for loop so that it iterates over the inner_transaction_targets and appends the results to a list. Finally, you return the list with all the results, indented aligned with the if statement, outside the for loop.
I've been write this practice program for while now, the whole purpose of the code is to get user input and generate passwords, everything almost works, but the replace statements are driving me nuts. Maybe one of you smart programmers can help me, because I'm kinda new to this whole field of programming. The issue is that replace statement only seems to work with the first char in Strng, but not the others one. The other funcs blower the last run first and then the middle one runs.
def Manip(Strng):
#Strng = 'jayjay'
print (Strng.replace('j','h',1))
#Displays: 'hayjay'
print (Strng.replace('j','h',4))
#Displays: 'hayhay'
return
def Add_nums(Strng):
Size=len(str(Strng))
Total_per = str(Strng).count('%')
# Get The % Spots Position, So they only get replaced with numbers during permutation
currnt_Pos = 0
per = [] # % position per for percent
rGen = ''
for i in str(Strng):
if i == str('%'):
per.append(currnt_Pos)
currnt_Pos+=1
for num,pos in zip(str(self.ints),per):
rGen = Strng.replace(str(Strng[pos]),str(num),4);
return rGen
for pos in AlphaB: # DataBase Of The Positions Of Alphabets
for letter in self.alphas: #letters in The User Inputs
GenPass=(self.forms.replace(self.forms[pos],letter,int(pos)))
# Not Fully Formatted yet; you got something like Cat%%%, so you can use another function to change % to nums
# And use the permutations function to generate other passwrds and then
# continue to the rest of this for loop which will generate something like cat222 or cat333
Add_nums(GenPass) # The Function That will add numbers to the Cat%%%
print (rGen);exit()
I'm new to Python and trying to figure out a rather simple way to count the output of a defined function. I want to count the number of unique users who have replied to a given username by defining a function to do this.
st='#'
en=' '
task1dict={}
for t in a,b,c,d,e,f,g,h,i,j,k,l,m,n:
if t['text'][0]=='#':
print('...'),print(t['user']),print(t['text'].split(st)[-1].split(en)[0])
user=t['user']
repliedto=t['text'].split(st)[-1].split(en)[0]
task1dict.setdefault(user, set())
task1dict[user].add(repliedto)
task1dict['realDonaldTrump'].add('joeclarkphd')
This returns what is below when I enter
print(task1dict)
{'datageek88': {'fundevil', 'joeclarknet', 'joeclarkphd'},
'fundevil': {'datageek88'},
'joeclarkphd': {'datageek88'},
'realDonaldTrump': {'datageek88', 'joeclarkphd'},
'sundevil1992': {'datageek88', 'joeclarkphd'}}
I then want to print all the Twitter users who replied to a certain user for example, all the people who replied to datageek88 is done by
def print_users_who_got_replies_from(tweeter):
for z in task1dict:
if tweeter in task1dict[z]:
print(z)
This prints me what is below when I enter:
print_users_who_got_replies_from('datageek88')
fundevil
joeclarkphd
sundevil1992
realDonaldTrump
Now, I want to count the number of replies by defining a function that then prints how many people replied to a user. This function should return the answer as a number (4), but I can't seem to get that part to work, any suggestions or help? Thanks! I have tried using the len() function but can't seem to get that to work, although it might be the answer.
Rule of thumb: when you have a function that prints many things, and you think "ok now how do I interact with those values that were printed?", that's a signal that you should be appending those values to a list rather than printing them.
In this case, the most straightforward modification to the code would be
def get_users_who_got_replies_from(tweeter):
result = []
for z in task1dict:
if tweeter in task1dict[z]:
result.append(z)
return result
seq = get_users_who_got_replies_from('datageek88')
for item in seq:
print(item)
print("Number of users who got replies:", len(seq))
Bonus advanced approach: strictly speaking, you don't need a whole function just to create and return one list based on the contents of another iterable. You could do it with a list comprehension:
seq = [z for z in task1dict if 'datageek88' in task1dict[x]]
for item in seq:
print(item)
print("Number of users who got replies:", len(seq))
I have two instances in my program: agents and firms.
I want a new class to work so that I can control the assignment of agents to firms.
The class I created has two dictionaries. I add posts and candidates to each dictionary. Each dictionary is keyed by the firm or agent ID. I had it work in other modules of my program.
I call the method to assign_post that would match candidates to posts. But it does not seem to work.
The whole class is:
class Posting(object):
def __init__(self):
self.available_postings = {}
self.candidates = {}
def add_post(self, firm):
self.available_postings[firm.get_firm_id()] = firm
def add_candidate(self, agent):
self.candidates[agent.get_id()] = agent
def assign_post(self):
# Rank positions by wage and rank employees by qualifications
# Make a match
while len(self.candidates) > 0 and len(self.available_postings) > 0:
# Best qualification
dummy_best = self.candidates.popitem()
for key in self.candidates.keys():
if dummy_best.get_qual() > self.candidates[key].get_qual():
dummy_best = self.candidates[key]
# Higher wage
dummy_higher = self.available_postings.popitem()
for key in self.available_postings.keys():
if dummy_higher.set_wage_base() > self.available_postings[key].set_wage_base():
dummy_higher = self.available_postings[key]
# Assignment. Firm has method add_employee
dummy_higher.add_employee(dummy_best)
# Remove agent and firm from list
del self.available_postings[dummy_higher.get_firm_id()]
del self.candidates[dummy_best.get_id()]
The mistake in your code is that you lose the item that received frompopitem(), in the case where it is not the best/higher. Try to receive element without removing it from dict, do assignment and after that remove it.