On 30/05/14 14:14, Ritwik Raghav wrote:
I joined the topcoder community tomorrow and tried solving the
PersistentNumber problem:
Time travel! I love it already... :-)
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:
You seem to have solved the problem.
Your code could be cleaned up a little but it seems
to work. The fact that the exercise asks for a self
argument suggests that it is supposed to be part of
a class definition.
Is there a class definition anywhere that you are
supposed to extend?
|Some comments on the code below:
def getPersistence(n,count = 0)
Since you never get passed count as an argument you
could just make it a variable. You only need it as
an argument if you use recursion but the problem
didn't ask for that...
product = 1
if len(str(n)) == 1:
return count
else:
a = str(n)
for i in range(len(a)):
product *= int(a[i])
This is not good Python style.
Its better to use
for c in a:
product += int(c)
count += 1
return getPersistence(product,count)
Rather than using recursion you could have used
a while loop (untested code!):
if n < 10:
return 0
product = 1
while True:
count += 1
a = str(n)
for c in a:
product *= int(c)
if product < 10:
break
return count
Now plz help me to convert the above code in specified format. Or help
me understand how to recreate the function as specified.
You have created a function that does what is needed, it just doesn't
have a self parameter. self is only used when the function is part of a
class definition.
Without sight of the class that it should be part of we can't offer much
more help.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor