# [Tutor] Mutable data type in python

Anshu Kumar anshu.kumar726 at gmail.com
Sat Oct 3 04:46:50 CEST 2015

```Hi Alan,

I was trying to solve a simple dynamic programming problem.

It goes like this. I have an input integer and i can choose to divide it by
two or three or subtract by one to reduce it to one. there is a condition
the number has to be divisible by 2 or 3 if we are dividing by two or three
respectively. I have to get shortest path to reduce input number to 1 by
using combination of either divide by three or two or subtract one.

so let suppose i have number 16 as input it will be reduced to 1 in 5
number of minimal steps 16-->16-1 = 15 -->15/3 = 5-->5-1= 4--> 4/2=2-->2/2
=1

so i wrote a simple program like this

depth = float('inf')

def findMinDepthPath(n,counter):
global depth
if(n== 1 and counter < depth):
depth = counter
elif(( n==2 or n==3) and counter < depth):
depth = counter + 1
else:
if(counter < depth):
if(n%3 == 0):
findMinDepthPath(n/3,counter + 1)
if(n%2 == 0):
findMinDepthPath(n/2,counter + 1)
findMinDepthPath(n-1,counter +1)

def getMinDepthPathLength(n):
global depth
depth = float('inf')
findMinDepthPath(n,0)
return depth

it works fine with global variable or a list type parameter for depth but i
am looking for a way where i would be able to use a parameter which will be
shared across all invocation and it should certainly not be a list coz i
don't need a list

Anshu

On Sat, Oct 3, 2015 at 5:05 AM, Alan Gauld <alan.gauld at btinternet.com>
wrote:

> On 02/10/15 17:52, Anshu Kumar wrote:
>
> When we invoke the same function inside a function (recursive function), i
>> want to keep track of some data across all function invocation so i should
>> have shareable type but built in data types string, int are not helping as
>> they are immutable they are changed while next invocation.
>>
>
> Show us some code and we will understand exactly what you are struggling
> with. I think I know, but it would be easier if
> you give a specific short example.
>
> I could use lists which are mutable but sometimes i find it not suitable
>> for example when i need only single number or string.
>>
>
> You can create a closure using a list, or you could use a global
> or you could just use a lot of parameters/return values. But
> without seeing exactly what you are trying to do its difficult
> to know which options suit you best.
>
>
> --
> 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
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
```