[Tutor] self keyword in recursive function
Ritwik Raghav
ritwikraghav14 at gmail.com
Sat May 31 07:16:33 CEST 2014
Peter Otten wrote:
>Ritwik Raghav wrote:
>
>> I joined the topcoder community tomorrow and tried solving the
>> PersistentNumber problem:
>> "Given a number x, we can define p(x) as the product of the digits of x.
>> We can then form a sequence x, p(x), p(p(x))... The persistence of x is
>> then defined as the index (0-based) of the first single digit number in
>> the sequence. For example, using 99, we get the sequence 99, 9*9 = 81,
8*1
>> = 8. Thus, the persistence of 99 is 2. You will be given n, and you must
>> return its persistence."
>>
>> It asks to define a function def getPersistence(self, n). I solved the
>> problem in IDLE. My code is:
>>
>> def getPersistence(n,count = 0):
>> product = 1
>> if len(str(n)) == 1:
>> return count
>> else:
>> a = str(n)
>> for i in range(len(a)):
>> product *= int(a[i])
>> count += 1
>> return getPersistence(product,count)
>>
>> Now plz help me to convert the above code in specified format. Or help me
>> understand how to recreate the function as specified.
>
>The "topcoder" site is probably infested with the world view of Java where
>every function is a method inside a class. You may have to wrap your code
>into something like
>
>class PersistentNumber:
> def getPersistence(self, n, count=0):
> ... # your code with a minor change (*)
>
>
>(*) Inside the method the recursive call becomes
>
> self.getPersistence(product, count)
>
>instead of just
>
> getPersistence(product, count)
It has again given some error I do not understand. This time my code is:
count = 0
def getPersistence(self,n):
product = 1
if len(str(n)) == 1:
return self.count
else:
a = str(n)
for i in a:
product *= int(i)
self.count += 1
return self.getPersistence(product)
and the error is:
Correct Return Value: No
Answer check result:
Result must be not null.
Execution Time: 0.017s
Peak memory used: 24.551MB
abnormal termination (exit 1)
Standard Output:
Standard Error:
Traceback (most recent call last):
File "Wrapper.py", line 182, in <module>
AttributeError: 'module' object has no attribute 'PersistentNumber'
I do not understand what it is trying to tell me? I tried to test it for 99.
--
Ritwik Raghav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140531/01aaa841/attachment.html>
More information about the Tutor
mailing list