python - list variable not storing proper result in recursion

2024/10/15 21:20:11

I am trying to store all possible parenthesisation of a list through recursion.

Example: printRange(0,3) Answer will be [[0],[1], [2]], [[0], [1, 2]], [[0, 1], [2]], [[0, 1, 2]]

I could get a right answer when i tried to print it in side the function.When i try to store the result and print it after i am not getting the desired result.

The code is as follows:

res=[]
def printRange(st,size,cans=[]):if(st==size):res.append([]+cans)print cansl=[]for i in range(st,size):l.append(i)tmp=[]+canstmp.append(l)printRange(i+1,size,[]+tmp)printRange(0,3)
print res

When i run the above code i got:

[[0], [1], [2]][[0], [1, 2]][[0, 1], [2]][[0, 1, 2]][[[0, 1, 2], [1, 2], [2]], [[0, 1, 2], [1, 2]], [[0, 1, 2], [2]], [[0, 1, 2]]]

why res variable is not storing the intended result?

Answer

This is happening because cans is a list of lists, and those inner lists get mutated. You need to append a deep copy of cans to res, i.e. a copy that makes copies of the internal lists. You can do that with deepcopy from the copy module, or just write a simple deepcopy that works for a list of lists.

Here's a repaired version of your code.

#from copy import deepcopydef deepcopy(list2d):return [u[:] for u in list2d]res = []
def printRange(st, size, cans=[]):if(st == size):res.append(deepcopy(cans))print cansl = []for i in range(st, size):l.append(i)tmp = [] + canstmp.append(l)printRange(i+1, size, tmp)printRange(0, 4)
print res

output

[[0], [1], [2], [3]]
[[0], [1], [2, 3]]
[[0], [1, 2], [3]]
[[0], [1, 2, 3]]
[[0, 1], [2], [3]]
[[0, 1], [2, 3]]
[[0, 1, 2], [3]]
[[0, 1, 2, 3]]
[[[0], [1], [2], [3]], [[0], [1], [2, 3]], [[0], [1, 2], [3]], [[0], [1, 2, 3]], [[0, 1], [2], [3]], [[0, 1], [2, 3]], [[0, 1, 2], [3]], [[0, 1, 2, 3]]]

Note that it's generally not a good idea to use a list or other mutable object as a default argument because default arguments are assigned when the function is defined, not when it's called, and that can cause surprising behaviour. It doesn't actually cause problems for your code, but it's still a good idea to avoid default mutable args unless you need that "interesting" behaviour, eg so it can be used as a memoization cache, and even then you should use a comment explaining that you're doing it on purpose. :) See “Least Astonishment” and the Mutable Default Argument for further details.


I would approach this task in a slightly different way, with one of my favourite "toys": a recursive generator.

def brackets(n):if n == 0:yield [[0]]else:for seq in brackets(n - 1):yield seq + [[n]]yield seq[:-1] + [seq[-1] + [n]]for seq in brackets(3):print seq

output

[[0], [1], [2], [3]]
[[0], [1], [2, 3]]
[[0], [1, 2], [3]]
[[0], [1, 2, 3]]
[[0, 1], [2], [3]]
[[0, 1], [2, 3]]
[[0, 1, 2], [3]]
[[0, 1, 2, 3]]

If you do actually want a list containing all the results, just pass the generator to the list constructor:

res = list(brackets(2))
print res

output

[[[0], [1], [2]], [[0], [1, 2]], [[0, 1], [2]], [[0, 1, 2]]]
https://en.xdnf.cn/q/117790.html

Related Q&A

Embedding matplotlib canvas into tkinter GUI - plot is not showing up, but no error is thrown

Running the python python script below does not show the embedded matplotlib plot. However it also throws no error message. Upon running the script, it is supposed to display a GUI displaying 4 buttons…

Can I get rid of this b character in my print statement? [duplicate]

This question already has answers here:What does a b prefix before a python string mean?(2 answers)Closed 7 years ago.Im wondering what this b charcter is and why its appearing. Im also wondering if I…

Python tkinter: configure multiple labels with a loop

I have a window with multiple labels. Instead of configuring each label individually, I want to use a for loop to configure them.Basically, what I get from the below code is all labels are showing the …

How do you create a sitemap index in Django?

The Django documentation is very minimal and I cant seem to get this to work.Currently I have 3 individual sitemaps, and I would like to create a sitemap index for them: (r^sitemap1\.xml$, django.contr…

Numpy Append to Array

I’m building a project for the Raspberry Pi that turns a relay on and off random times in a specific time window. To manage the time slots, I want to use a two-dimensional array that’s generated dail…

Output of numpy.diff is wrong

heres my problem: I am trying to use numpy to compute (numerical) derivatives, but I am finding some problems in the value the function numpy.diff returns (and numpy.gradient as well). What I find is t…

Calculate Fibonacci numbers up to at least n

I am trying to make a function that allows a user to input a number and the result will be a list containing Fibonacci numbers up to the input and one above if the input is not in the series. For examp…

IEC 62056-21, implement the protocol over a gsm connection

The protocol IEC 62056:21 tells us how to deal with enegy meters, its quite easy!The part where I am stuck is the implementation over a GSM data channel. Normally I would set things like:300 baudrate …

Cannot install plyfile in Anaconda

When u=i try to run the commandconda install plyfilein windows command promptFetching package metadata ...........PackageNotFoundError: Package not found: Package missing in current win-64 channels: -…

Expected singleton: stock.move - Odoo v9 community

Im creating a stock.picking from fleet_vehicle_log_services with this method:@api.multi def create_picking(self):self.ensure_one()vals = {move_lines: self.move_lines.id,origin: self.name}picking = self…