Home > Enterprise >  Trying to get the old age level of a person from family dictionary
Trying to get the old age level of a person from family dictionary

Time:05-01

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

CodePudding user response:

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

CodePudding user response:

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_
  • Related