I am trying to get the old age level of a person from this dictionary:
d = {'Sıdıka': [{'Aziz': [{'Ahmet': [{'Kuzey': []}]}, {'Öznur': [{'Elif': []}, {'Yiğit': []}]}, {'İlknur': [{'Nurullah': []}, {'Büşra': []}]}, {'İlker': [{'Melih': []}]}]}]}
“Sıdıka” is the eldest one and I want to determine her level (which is 3 (Ex. “Sıdıka” is “Kuzey”’s
father’s, father’s, mother. Which makes 3)).
How can i achieve that?
I tried:
Recursion, but couldn’t figure it out how.
My attempt:
def new(self,dict,count,max):
for i in dict:
print(dict[i])
if len(dict[i])!=0:
for i in dict[i]:
self.new(self,i,count,max)
count+=1
print(count)
else:
return count
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Here is a simple recursion in one statement (assuming d the input dictionary).
You can uncomment the print to see how it works.
def level(d, lvl=0):
#print(f'level {lvl}:', d)
return max((lvl, *(level(l, lvl=lvl+1)
for v in d.values()
for l in v)
))
level(d)
Output: 3
Method 2
I think i got the solution:
self.max_= 0
def new(self,dict,count):
for i in dict:
print(dict[i])
if len(dict[i])!=0:
for i in dict[i]:
print(self.max_)
self.new(self,i,count)
count+=1
# print(count)
else:
if count>self.max_:
self.max_=count
return self.max_
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0