[Tutor] Mutable data type in python
Alan Gauld
alan.gauld at btinternet.com
Sat Oct 3 20:55:56 CEST 2015
On 03/10/15 19:10, C Smith wrote:
>> Here is my modified version which I think works as you want:
>>
>> def findMinDepthPath(n):
>> if n <= 0: raise ValueError
>> elif n==1:
>> return 0
>> elif n==2 or n==3:
>> return 1
>> else:
>> d1 = findMinDepthPath(n-1)+1
>> d2 = d3 = (d1+1) # initialize to higher than d1
>>
>> if n%3 == 0:
>> d3 = findMinDepthPath(n/3)+1
>> if n%2 == 0:
>> d2 = findMinDepthPath(n/2)+1
>>
>> return min(d1,d2,d3)
>>
>>
>> n = int(raw_input('N? '))
>> print "Minimum depth = ", findMinDepthPath(n),'\n'
> Doesn't this only look one level deep? Is the poster asking for
> something that would traverse all possible paths and then check for
> the shortest?
No, this is a recursive function which keeps calling itself with smaller
values of n until it reaches 1-3, at which point it returns a known result.
Here is an example of the factorial() function written recursively in a
similar style, it might be easier to see how it works:
def square(n):
print n # show the recursion
if n <= 1: return 1
else: return n * factorial(n-1)
print factorial(5)
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list