[Tutor] recursive problem
Shashwat Anand
anand.shashwat at gmail.com
Thu Sep 9 11:38:10 CEST 2010
On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben <rwobben at hotmail.com> wrote:
> Hello,
>
> I have this :
>
> def recursive_count(target, nested_num_list):
> """
> >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
> 4
> >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
> 2
> >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
> 0
> >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
> 6
> """
> for element in nested_num_list:
> if type(element) == type([]):
> test = recursive_count(target, element)
> print element, target
> if element == target :
> count = count + 1
> return count
>
> if __name__ == "__main__":
> import doctest
> doctest.testmod()
>
>
> Now I get this message :
>
> UnboundLocalError: local variable 'count' referenced before assignment
>
It is because you are doing count = count + 1
But where is count defined.
>
> But if I do this :
>
> def recursive_count(target, nested_num_list):
> """
> >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
> 4
> >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
> 2
> >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
> 0
> >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
> 6
> """
> count = 0
> for element in nested_num_list:
> if type(element) == type([]):
> test = recursive_count(target, element)
> print element, target
> if element == target :
> count = count + 1
> return count
>
> if __name__ == "__main__":
> import doctest
> doctest.testmod()
>
> The count will always be 0 if a nested list is being found.
>
> What's the python way to solve this
>
I am not sure what do you want to achieve by this ?
What is the problem statement ?
>
> Roelof
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
--
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/092878a1/attachment.html>
More information about the Tutor
mailing list