1

I am new to C and trying to learn by comparison with Python.

My question is trivial, but I still need some explanations from experts. Here is a Python nested list structure:

L = [1, [2, [3, 4], 5], 6, [7, 8]]

And here is an interesting piece of code (taken from 'Learning Python' by Lutz) to handle nested structures (sum elements):

def sumtree(L):
    tot = 0
    for x in L:
        if not isinstance(x, list):
            tot += x
        else:
            tot += sumtree(x)
    return tot

If I pass L into this function I will get 36, which is a sum of elements in L. How exactly can nested lists and this particular function be translated into C?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
user2376997
  • 501
  • 6
  • 22
  • 1
    Arrays in C are fixed length. If you want variable length, you will need a structure, involving pointers. Try reading up on structures and linked lists. – Mawg says reinstate Monica Dec 04 '17 at 07:05
  • Your question is perfectly legitimate. The answer, however, is that C doesn't support "list" as as a built-in construct. You have to invent a "list" yourself, with constructs like "struct" or "array". – paulsm4 Dec 04 '17 at 07:13
  • Python is a dynamic type language, with a lot of difference with C. You can't expect code in C like in python. – Stargateur Dec 04 '17 at 07:20
  • I don't expect the same code, I want the same result first of all – user2376997 Dec 04 '17 at 07:21

1 Answers1

2

What type is every element of L? It can be a number (an int for example in C), or even a list (it's typical for a list to be implemented with structs in C).

In order to achieve that, you would need a generic list (i.e. that the data of every node is of type void*). Notice that C doesn't provide a list from the standard library, you have to write one (here is an example).

Then, in order to get the sum, you would do something like that:

int sumtree(struct listnode * L) {
    int tot = 0;
    while (L != NULL) {
        if(L.data /* TODO: check if it is a number*/)
            tot += L.data;
        else /* L.data is a sublist */
            tot = sumtree(L.data);
        list = list->next;
    }
    return tot;
}

In order to get the type, you need to follow this answer: How do I check if a variable is of a certain type (compare two types) in C?

However, such nested lists in C are not common, and I would advise you to re-approach the issue.

gsamaras
  • 71,951
  • 46
  • 188
  • 305