|
I am trying to find a way to count the distinct list items within any given nest level within a list. I think the sum of all of these should actually add up to "Deep Count". I have Deep Count working but I am stuck with the sub totals. I am using len() to determine the number on a given nested level but can't code the recursive piece properly(or traverse ?). I am also using the is_list function to test the items to see if they are lists. I know that for example the following list(al) should return 2 items for the first nest, representing the distinct value 'a' + the second list but I am interested in the distinct values. Any suggestions would be a big help. and would allow me to finish CS101 finally :) al = ['a', ['b', ['c','e']]]
|
|
ThThere are 2 mistakes. First is that if the element is not list, your procedure will not return anything. So your code need to be like this:
and the second is that you don't use recursion. But I cannot help you with the second problem till the deadline because it will provide you with the answer for the exam task. But you are close to the right code. So read again lecture about recursion. Hope you will manage with it! |
Not sure what you mean bu "count the distinct list items within any given nest level within a list". In your example, what would the "distinct values" you are interested in be?
Also noticed the return statement in your code may not be indented correctly. Shouldn't it be at the same indent as "for e in p:" in order to return branch?
Of course, all the lines under your def line should be indented as well.
Thanks, indent was just a cut and paste problem and branch was in the wrong spot. The distinct values in the example above would have been 'a' for the first nest, 'b' in the second nest and 'c' + 'e' in the last nest. Think I found another way to finish the question.