Linking elements of a list as a tree [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a python list that looks like this for example :
[Product(parent=tube,child=spokes), Product(parent=bicycle, child=wheel), Product(parent=wheel,child=tube)]
Where Product is a python class with two members parent and child.
The Products could appear in any order in the list.
What would be the most efficient one liner to achieve the following :
Given an input spokes for example , return the `root of the tree` , bicycle in this case.
What have i tried so far : inefficient for loops that does not give the right results when the Product does not appear in the same order each time.

You do not write how strong assumption you can apply to data (if it is always proper tree). So my code check some conditions to not stick in infinity loop.
def find_root(pr_list, child):
if len(pr_list) == 0:
return None
child_translate_dict = {x.child: x for x in pr_list}
potential_root = child
count = 0
while count < len(pr_list):
if potential_root not in child_translate_dict:
return potential_root
else:
potential_root = child_translate_dict[potential_root].parent
count += 1
return None
and shorter version
def find_root(pr_list, child):
child_translate_dict = {x.child: x for x in pr_list}
while child in child_translate_dict:
child = child_translate_dict[potential_root].parent
return child

Here is a pseudo code for your problem :
def recursiveRootFinder(child,theList):
for(i in theList):
if (i.child==child):
child=recursiveRootFinder(i.parent,theList)
return child
You can use lambda definition to implement it in one line like that :
lambda child,theList: recursiveRootFinder(i.parent,theList) for i in list if i.child==child if [1 for i in list if i.child==child]!=[] else child

Related

How would I add the results of a 'for' loop into a dictionary? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I am required to take 52 random outputs of cards. I got that in a for loop. The problem is, I need to save that output inside a variable.`
import random
r=random.randint(0, 9)
cards={'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2={}
for i in range(52):
global res
res = key, val = random.choice(list(cards.items()))
print("Your deck contains " + str(res))
cards2.update(i) # All output should go in here
I tried using cards2.update, but it didn't work.
I also tried using cards2.(keys).
I just need to create 52 random samples and store them as dictionary value pairs.
First remove the double assignment (res = key, val). And I don't see any point in using a global variable here. Just do _dict[key] = value as shown below, and it will work fine. Also remember that you can’t get all 52 random cards, because if the key exists then the value will be replaced.
import random
r = random.randint(0, 9)
cards = {'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2 = {}
for i in range(52):
key, val = random.choice(list(cards.items()))
cards2[key] = val
print(cards2)

Python continue and break usage [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I need to solve the following problem and I assume I have to use continue and break logic.
I have to create an empty to do list and iterate over the dictionary of tasks. I need to add tasks that contain the substring "organize" and once the length of the to do list reaches 2 tasks I break the loop. *
tasks = {
0 : ['Reorganize the cabinet'],
1 : ['Give the dog a bath', 'Create a twitter thread'],
2 : ['Learn python dictionary'],
3 : ['Take a walk'],
4 : ['Go grocery shopping'],
5 : ['Update Facebook'],
6 : ['Respond to emails'],
7 : ['Walk the dog']
}
I could solve the second part of adding the tasks that contain the substring "organize" and could iterate through the length of tasks to filter tasks that are not more than 2. Yet, I can't find the way how to combine two conditions into one.
Put an if statement in the loop that checks the length of the to do list, and breaks out of the loop when it reaches 2.
todo_list = []
for task in tasks.values():
if any('organize' in item for item in task):
todo_list.append(task)
if len(todo_list) == 2:
break
This will work :
to_do_list = []
for task in tasks.values():
for i in task :
if 'organize' in i:
to_do_list.append(i)
if len(to_do_list) == 2:
break
does this do the job:
to_do_list = []
for value in tasks.values():
to_do_list.append([val for val in value if 'organize' in val])
if len(to_do_list) == 2:
break
If you want a flattened list of items, replace to_do_list.append with to_do_list.extend

How to convert list of strings into floats? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have the list of data:
rfd_per_neihborhood_15 = ['75.8', '108.5', '76.6', '96.4', '104.8', '95.8', '165.8', '128.9']
I need to convert it into float in order to calculate the average and etc.
I've tried:
list(map(float, rfd_per_neihborhood_15))
list(np.float_(rfd_per_neihborhood_15))
for item in list:
float(item)
a = rfd_per_neihborhood_15
floats = []
for element in a:
floats.append(float(element))
print(floats)
Nothing is working, it's throwing ValueError: could not convert string to float: '-'
The problem could be that there is an element in your list which has a - (hyphen). To tackle that, you can use try-except in the following manner:
rfd_per_neihborhood_15 = ['75.8','108.5','76.6','96.4','104.8','95.8','165.8','128.9','4-4']
def safe_float(x):
try:
return float(x)
except:
print(f"Cannot convert {x}")
#Returning a 0 in case of an error. You can change this based on your usecase
return 0
list(map(safe_float, rfd_per_neihborhood_15))
Output:
Cannot convert 4-4
[75.8, 108.5, 76.6, 96.4, 104.8, 95.8, 165.8, 128.9, 0]
As you can see, my code gracefully handled the exception and returned a 0 in place of the last element '4-4'. Alternatively, you could also return a NaN.
You could try this:
rfd_per_neihborhood_15 = ['75.8', '108.5', '76.6', '96.4', '104.8', '95.8', '165.8', '128.9']
# shortening the name to r_pn15
r_pn15 = rfd_per_neihborhood_15
floated_list = []
for item in r_pn15:
r_pn15.append(float(item))
print(floated_list)

Python create nested dict in for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to created a nested dictionary but I have a problem inside the for loop, at least is what I'm thinking.
I do several requests based on args passed but when I try to add values to the nested dict created before it just adds the last arg passed.
I'll show the code and the output.
def api_metrics():
my_list = []
my_dict_1 = {}
number = len(my_metrics)
metricz = range(number)
for indice in metricz:
my_dict_1[indice] = {}
for metric in my_metrics:
urlnotoken = ""
urlnotoken = urlnotoken.replace(" ","%20")
preurl = urlnotoken + "&dateToken="+expirationDate
msg = preurl + apikey
token = calcMd5(msg)
finalurl = "http://"+host+preurl+"&token="+token
data_get = requests.get(finalurl, headers=app_headers)
json_data = json.loads(data_get.text)
metrics_path = json_data['data'][0]['metrics'][0]
metric_name = metrics_path['label']
metric_value = metrics_path['values'][0]['data'][0][1]
metric_unit = metrics_path['magnitudes']['y']
my_list.append(metric_name)
my_list.append(metric_value)
my_list.append(metric_unit)
number = len(my_metrics)
metricz = range(number)
my_values = metric
for entry in my_dict_1.keys():
my_dict_1[entry] = metric
return(my_dict_1)
And the output
{0: 'avgRenditionSwitchTime', 1: 'avgRenditionSwitchTime', 2: 'avgRenditionSwitchTime', 3: 'avgRenditionSwitchTime', 4: 'avgRenditionSwitchTime'}"
This should output the different args passed. I have moved the code inside and outside the loop, I've read lots of posts but I need further help!
Cheers.
In here:
for entry in my_dict_1.keys():
my_dict_1[entry] = metric
You are assigning the value of metric to all your dict (my_dict_1) items. Reason why 'it just adds the last arg passed'.
Without cleaning up your code, here's the patch to fix your issue:
for i, metric in enumerate(my_metrics):
...
my_dict_1[i] = metric

Implementing treeset data structure store and read in VBA / Python/ Shell [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a text file like this
LEVEL=3
LEVEL1=CLASS7
LEVEL2=ROLLNO1
LEVEL3=MALE
JOHN,12
LEVEL2=ROLLNO2
LEVEL3=FEMALE
JULIA,11
We need to read this file and need output like
CLASS7|ROLLNO1|MALE|JOHN|12
CLASS7|ROLLNO2|FEMALE|JULIA|11
1st LELVEL=3 means maximum LEVEL present in the file.
Here LEVEL 1 is common, but in actual data sometimes LEVEL 1 and 3
can be common when maximum LEVEL is say 7.Basically there is no clear
pre-defined pattern.
I have solved it in VBA using normal array structure but when file becomes
very big and maximum LEVEL becomes more( like more than 10)
it becomes slow.
Then I tried to read more things and came to know using
treeset data structure and iterator kind of things it works fast.
But this things possible in Java.
How we can do it in VBA ?
If possible in shell or python that is also ok.
here is a little python approache, but very specific on you string formating, with "text.txt" containing your text:
f = open( "text.txt", 'r' )
text = f.readlines()
f.close()
d = { }
for line in text :
pair = line.split( '=' )
if len( pair ) == 2 : # save Levels as pairs in dict
d[pair[0].strip()] = pair[1].strip()
else : line without level means time for output
out = [] # gather the values in here
try :
for i in range( 1, int( d['LEVEL'] ) + 1 ) : # number of levels (1-based)
out.append( d['LEVEL' + str( i )] ) # add every level
except KeyError :
pass
out += line.split( ',' ) # add current line
out_as_string = '|'.join( out ) # convert to string with "|"
print( out_as_string )
outputs:
CLASS7|ROLLNO1|MALE|JOHN|12
CLASS7|ROLLNO2|FEMALE|JULIA|11

Categories

Resources