[Tutor] Mutable data type in python

Alan Gauld alan.gauld at btinternet.com
Sat Oct 3 14:28:34 CEST 2015


On 03/10/15 09:23, Anshu Kumar wrote:
> Hi Alan,
>
> I have given a wrong example of 16 . I am sorry for it. You are 
> correct it will take only 4 turns.
>
> If i consider your solution for number 10
>
> it will go like this 10-->10/2 =5 --> 5-1=4--> 4/2 =2-->2/2 =1 which 
> gives 4 as output but answer would be  in 3 steps 
> 10-->10-1=9-->9/3=3-->3/3=1
>
> So we must consider every path /3, /2 and -1 and try to find out 
> shortest one

Ah, OK I see.

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'

 >I know list and sets can be used do we have any other data structure 
in python
 > which would be mutable and not a sequence?

You could use a dictionary but that is also a type of sequence...

So a class is the obvious non-sequential candidate.

class Store:
     def __init__(self, value = 0):
         self.value = value

You can then pass an instance of the class and modify its value.

-- 
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