Re: [Tutor] Need help solving this problem
Hi Raj, I'm another learner, I used the following: >>> def toss(n): heads = 0 for i in range(n): heads += random.randint(0,1) return heads, n-heads >>> print "%d heads, %d tails" % toss(100) Best of luck in your python endeavors! 2009/6/10 Raj Medhekar : > I have been teaching myself Python using a book. The chapter I am on > currently, covers branching, while loops and program planning. I am stuck on > on of the challenges at the end of this chapter, and I was hoping to get > some help with this. Here it is: > > Write a program that flips a coin 100 times and the tells you the number of > heads and tails. > > I have tried to think about several ways to go about doing this but I have > hit a wall. Even though I understand the general concept of branching and > looping, I have been having trouble writing a program with these. I look > forward to your reply that will help me understand these structures better. > > Sincerely, > Raj > > > ___ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] variable within function retains value
Hi All, I'm trying to write a function that flattens a list. However after I call the function more than once, it appends the result (a list) from the second call with the first. I can get around it by either setting the list to an empty one before calling the function, but I would like to keep it in the function, another alternative I found was to pass an empty list as an argument. Can someone explain how python keeps track of variables within functions (I was expecting the variable to be destroyed after a value was returned). Also what is a better way to handle this? Thanks >>> def flatten(myList,start=[]): """ Flatten nested lists >>> flatten([1,[2,[3,4],5]],[]) [1, 2, 3, 4, 5] """ for i in myList: if type(i) != list: start.append(i) else: flatten(i,start) return start >>> flatten([1,[2,[3,4],5]]) [1, 2, 3, 4, 5] >>> flatten([1,[2,[3,4],5]]) [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] >>> flatten([1,[2,[3,4],5]],[]) [1, 2, 3, 4, 5] 2009/6/18 Luke Paireepinart : > Karen Palen wrote: >> >> Which appears to be merely the return code, not the stdout! >> >> It looks like I need to set some variable in IDLE, but I can't figure out >> exactly what is needed here. >> >> Can anyone point me to an answer? >> > > Well, Karen, according to my IDLE (admittedly it's 2.6 not 3.0 so it may not > agree), call only returns the return code. > You can check on your system by doing the following: > > IDLE 2.6.2 >>> import subprocess help(subprocess.call) > > which will print out the docstring for the method: > > Help on function call in module subprocess: > > call(*popenargs, **kwargs) > Run command with arguments. Wait for command to complete, then > return the returncode attribute. > The arguments are the same as for the Popen constructor. Example: > retcode = call(["ls", "-l"]) > > I believe what's happening is that you are confused about the presence of > STDOUT in IDLE. > > In a normal console window, when you call a program (such as "ls"), stdout > is directed at the screen (the console window.) > So what's happening in the first example (the non-idle one) is: > > open subprocess and execute an "ls" call > - the subprocess prints out the result of the "ls" call > -subprocess finishes > process finishes > > Now the key here is that in this case, both of these have the same stdout > (the screen), which is the default stdout. > > However, when you run from an IDLE prompt, your stdout is not going to be > the default. > check it out if you want: > import sys print sys.stdout > > > Notice that this is not a standard stdout. > In a normal Python window, > import sys print sys.stdout > ', mode 'w' at 0x00A43070> > > it's not the same stdout as IDLE has. > > So what's happening when you run the command from IDLE: > open subprocess and execute an "ls" call > -subprocess starts, executes "ls", prints result to _its_ stdout (which is > not IDLE's stdout, remember!) > -subprocess executes, output goes bye bye > your process ends as well > > So the problem is that the stdout of the "ls" command is appearing in some > location that you cannot see. > As for ways to remedy this - I don't know. The idea here, though, is that > even though the regular Python version has the side-effect that it outputs > it in the console, that's not necessarily what you want it to do. The > reason is that you have no way to access that data. > > Also you mentioned that IDLE prints out a 0. This is only something that > IDLE's interpreter does. > For example x = "hello" x > 'hello' > > IDLE echoes the value of x. However, if you had the code > x = "hello" > x > > and you ran it (not in IDLE's interpreter) you would not get any output. > > What you should learn from this is > 1- IDLE is weird in many ways > 2 - that subprocess.call() is not meant to get data back from a call (look > at subprocess.Popen and its communicate() method for that) > 3 - sometimes things that appear to be outputs are side-effects/artifacts of > the environment you're running them in and can't be depended upon. > > HTH, > -Luke > ___ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] variable within function retains value
Excellent, thanks for that answer Kent. Also thanks for the link 2009/6/18 Kent Johnson : > On Thu, Jun 18, 2009 at 6:21 AM, karma wrote: >> Hi All, >> >> I'm trying to write a function that flattens a list. However after I >> call the function more than once, it appends the result (a list) from >> the second call with the first. I can get around it by either setting >> the list to an empty one before calling the function, but I would like >> to keep it in the function, another alternative I found was to pass an >> empty list as an argument. >> >> Can someone explain how python keeps track of variables within >> functions (I was expecting the variable to be destroyed after a value >> was returned). Also what is a better way to handle this? > > Default arguments are only evaluated once, when the function is > compiled, so the start list is shared between invocations of flatten. > This is a FAQ: > http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm > > Another solution - it's easy to rewrite flatten() so it doesnt' need a > default argument: > > In [1]: def flatten(myList): > ...: start = [] > ...: for i in myList: > ...: if type(i) != list: > ...: start.append(i) > ...: else: > ...: start.extend(flatten(i)) > ...: return start > > Kent > > PS Please don't quote unrelated questions when posting. > >> Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Eliminating consecutive duplicates in a list
I was playing around with eliminating duplicates in a list not using groupby. From the two solutions below, which is more "pythonic". Alternative solutions would be welcome. Thanks x=[1,1,1,3,2,2,2,2,4,4] [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] output: [1, 3, 2, 4] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Eliminating consecutive duplicates in a list
Hi Robert, Thanks for the link. However, I am looking for eliminating consecutive duplicates rather than all duplicates - my example wasn't clear, apologies for that. x=[1,1,1,3,2,2,2,4,4,2,2] [1 ,3 ,2 ,4 ,2 ] 2009/6/18 Robert Berman : > This might help: http://code.activestate.com/recipes/52560/ > > Robert > > > On Thu, 2009-06-18 at 15:15 +0200, karma wrote: >> I was playing around with eliminating duplicates in a list not using >> groupby. From the two solutions below, which is more "pythonic". >> Alternative solutions would be welcome. >> >> Thanks >> >> x=[1,1,1,3,2,2,2,2,4,4] >> >> [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] >> >> [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] >> >> output: >> [1, 3, 2, 4] >> ___ >> Tutor maillist - tu...@python.org >> http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] printing tree structure
Hi all , I have a nested list in the structure [root,[leftSubtree],[RightSubtree]] that I want to print out. I was thinking that a recursive solution would work here, but so far I can't quite get it working. This is what I have so far: Can someone suggest whether this is suited to a recursive solution and if so, what am I doing wrong. Thanks >>> L = ['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]] >>> def printTree(L): for i in L: if isinstance(i,str): print 'Root: ', i else: print '--Subtree: ', i printTree(i) >>> printTree(L) Root: a --Subtree: ['b', ['d', [], []], ['e', [], []]] Root: b --Subtree: ['d', [], []] Root: d --Subtree: [] --Subtree: [] --Subtree: ['e', [], []] # this shouldn't be here Root: e --Subtree: [] --Subtree: [] --Subtree: ['c', ['f', [], []], []] Root: c --Subtree: ['f', [], []] Root: f --Subtree: [] --Subtree: [] --Subtree: [] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] printing tree structure
Thanks all for the feedback. As you all rightly pointed out, I was confusing myself by not keeping a track of the recursion depth. Thanks again 2009/7/3 Alan Gauld : > > "karma" wrote > >> thinking that a recursive solution would work here, but so far I can't >> quite get it working. This is what I have so far: >> >> Can someone suggest whether this is suited to a recursive solution and > > Yes certainly > >> if so, what am I doing wrong. > >>>>> L = ['a', > > ['b', ['d', [], [] ], > ['e', [], [] ] > ], ['c', > ['f', [], [] ], [] > ] > ] > >>>>> def printTree(L): >> >> for i in L: >> if isinstance(i,str): >> print 'Root: ', i >> else: >> print '--Subtree: ', i >> printTree(i) >> > >>>>> printTree(L) >> >> Root: a >> --Subtree: ['b', ['d', [], []], ['e', [], []]] >> Root: b >> --Subtree: ['d', [], []] >> Root: d >> --Subtree: [] >> --Subtree: [] > > This is the end of the recursive call to printTree( ['d', [ [], [] ] ] > >> --Subtree: ['e', [], []] # this shouldn't be here > > This is the next element in printTree( ['d', [], []], ['e', [], []] ) > >> Root: e > > This is the start of printTree( ['e', [], [] ] ) > >> --Subtree: [] >> --Subtree: [] > > Now why do you think the line you highlighted is an error? > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ___ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor