Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you explain the following function?

def a(n):
    return max([len(n)] + [a(i) for i in n]) if isinstance(n, list) else 0

this was in a recent test of mine and i just can't get list comprehension down. So basically this function was supposed to return the length of the largest list (which is what i'm assuming based on the correct answers) I would have understood that if it weren't for this part of the function:

+ [a(i) for i in n])

when i see that part, it looks like it adds something to the length of the list it was iterating over. Can someone shed some light on the purpose of that part? more specifically the reason for the addition.

edit: so after looking at it more carefully..it looks like the function puts the length of the first list in a list, then puts the length of the next list and returns the max?... is this how it works?

like image 799
user3050527 Avatar asked Mar 08 '14 02:03

user3050527


People also ask

How do you explain a function?

A function is defined as a relation between a set of inputs having one output each. In simple words, a function is a relationship between inputs where each input is related to exactly one output. Every function has a domain and codomain or range. A function is generally denoted by f(x) where x is the input.

What are the 4 types of functions?

The types of functions can be broadly classified into four types. Based on Element: One to one Function, many to one function, onto function, one to one and onto function, into function.

What are functions explain with examples?

A function is a mapping from a set of inputs (the domain) to a set of possible outputs (the codomain). The definition of a function is based on a set of ordered pairs, where the first element in each pair is from the domain and the second is from the codomain.

WHAT IS function and explain its types?

A function is a relation between a set of inputs and a set of permissible outputs with the property that each input is related to exactly one output. Let A & B be any two non-empty sets; mapping from A to B will be a function only when every element in set A has one end, only one image in set B.


1 Answers

This function computes the length of the largest node in a tree (implemented as lists within lists). Perhaps with a bit of renaming and reording, it'll be clearer:

def longest_list_in_tree(tree):
    if not isinstance(tree, list):
        return 0 # This is a leaf-value of the tree, it has "length 0"

    own_length = len(tree)
    longest_descendant_of_each_subtree = [
        longest_list_in_tree(subtree) for subtree in tree
    ]

    return max([own_length] + longest_descendant_of_each_subtree)
like image 183
slezica Avatar answered Sep 30 '22 08:09

slezica