Re: [Tutor] adding users to tweets on a list
There was only Chris responding to the question so I removed the line above the quoted part in my responses that says "On Aug 6, 2013 11:36 PM, "Dave Angel" wrote:"... is that what's confusing? On Aug 6, 2013 11:36 PM, "Dave Angel" wrote: > Saad Javed wrote: > > > I want to add users to the tweet from the list, the no. of users added > > based on the length of the tweet. > > > This version should be a bit cleaner than what I've seen on this thread. > > #!/usr/bin/env python > > LIMIT = 140 > #(I use uppercase there to show it's a constant) > > def send(message, users): > output = message > while users: > while users and 1+len(output+users[0]) < LIMIT: > output += " " + users.pop(0) > if output == message: > print "message too long for user", user[0] > raise userError > print output > output = message > > lst = ['@saad', '@asad', '@sherry', '@danny', '@ali', '@hasan', > '@adil', '@yousaf', '@maria', '@bilal', '@owais'] > > > #string = raw_input('enter string: ') > #example string > string = ("These are my friends living in the same city as i am." > " I have known them for years. They are " > "good people in general. They are:") > > send(string, lst) > > BTW, you have a bunch of other messages on the thread which are replying > to the invisible man, posts that aren't (yet?) visible. Since you quote > him without attribution, we have no clue who you're commenting about. > > -- > DaveA > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] adding users to tweets on a list
On 07/08/13 15:41, Saad Javed wrote: There was only Chris responding Apparently he didn't CC the list so the rest of us didn't see it(*). is that what's confusing? It's not just the lack of attribution but the fact we just didn't see the post to which you are replying. (*)It is possible that Chris' mail is in the moderation queue, which I was hoping to visit tonight or tomorrow... In which case, watch this space... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Start multiple threads from Python
On 2013-08-05 12:17, Ryan Waples wrote: > Currently I am calling each analysis program one at a time with > subprocess.call(). This is working without a hitch, but as each analysis > can take a while to run, I want to try to speed things up. I realize I can > start three different python sessions to do this, but that just begs the > question how to do that from python? subprocess.Popen does not block unless you explicitly tell it to (by using communicate()). Perhaps that's what you want. >>> import subprocess >>> x = subprocess.Popen([ "sleep", "60" ]) >>> y = subprocess.Popen([ "sleep", "60" ]) >>> x.pid 3035 >>> y.pid 3036 pgp7_7NXZ0dcW.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Can anyone explain this
Can anyone explain this code below: import sys import os if __name__ == '__main__': sys.path.insert(0, "..") else: sys.path.insert(0, os.path.join( os.path.split(__file__)[0], '..')) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python to open a "example.jmp" file
I am trying to open a JMP file using python. Here is the code I found online: # -*- coding: cp1252 -*- from win32com.client import Dispatch jmp = Dispatch("JMP.Application") doc = jmp.OpenDocument("C:/Users/bdourass/Desktop/Python/example.jmp") doc.CreateOneWay This is the error I get: Traceback (most recent call last): File "C:\Users\bdourass\Desktop\Python\RunJMPusingPython.py", line 3, in jmp = Dispatch("JMP.Application") File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 108, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 85, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221005, 'Invalid class string', None, None) >>> I couldn't find much resources about the interaction between python and JMP pro software online All inputs are appreciated. Thanks in advance. Sam ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] adding users to tweets on a list
On 2013-08-06 18:36, Dave Angel wrote: > This version should be a bit cleaner than what I've seen on this thread. Our methods are almost the same, other than the fact that you don't use a generator, and you do the length validity check during the loop instead of preemptively, I'm not sure which I think is cleaner. I'm more inclined toward using more lines of code to clearly express the reason for the failure's conclusion, but either is perfectly valid and readable. Thanks for the alternative :-) On 2013-08-06 18:36, Dave Angel wrote: > BTW, you have a bunch of other messages on the thread which are replying > to the invisible man, posts that aren't (yet?) visible. Since you quote > him without attribution, we have no clue who you're commenting about. He is replying to me, but his client seems to not prepend any header to his quotes. I am new to this list and am still held in the moderation queue. Chris pgpDLqAd47rSw.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Converting a string to an integer
This message was originally HTML formatted. View in a HTML capable client to see the original version.\r\n\r\nI'm trying to convert from a string of digits such as x = [y:y+1] into an integer using int(x). the book says I can do this, but I get an error message saying no can do. Anybody tell me what's going on?___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] adding users to tweets on a list
On 08/06/2013 03:18 PM, Chris Down wrote: On 2013-08-06 18:36, Dave Angel wrote: This version should be a bit cleaner than what I've seen on this thread. Our methods are almost the same, other than the fact that you don't use a generator, and you do the length validity check during the loop instead of preemptively, I'm not sure which I think is cleaner. I'm more inclined toward using more lines of code to clearly express the reason for the failure's conclusion, but either is perfectly valid and readable. Thanks for the alternative :-) I didn't actually check whether that exception is valid; it's probably spelt wrong. On 2013-08-06 18:36, Dave Angel wrote: BTW, you have a bunch of other messages on the thread which are replying to the invisible man, posts that aren't (yet?) visible. Since you quote him without attribution, we have no clue who you're commenting about. He is replying to me, but his client seems to not prepend any header to his quotes. I am new to this list and am still held in the moderation queue. Thanks for the status, I didn't think about the moderation queue. Presumably the only reason he saw your messages already is you did a reply-all instead of a reply-list. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Trouble, Please Help!
Hello, I am currently working with the Python programming language and had a very basic question regarding the start up of Python. For some reason, when I open up the Command Prompt in my Windows 7 computer, I am unable to access python files. So when I type in the python command, I am able to start writing in python, but I cannot call other python files such as saying python helloworld.py. I think it might have something to do with where I am placing my files and the path of python? Not too sure though because of my lack of computer knowledge. When I do put in python helloworld.py into the command prompt line, the computer gives me a response of: "python: can't open file 'hello.py': [Errno 2] No such file or directory." I know for a fact that there does exist a file called hello.py though. Please help me if you can! Sincerely, Python_Beginner ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question
what exactly you want to do by [1,2,3] = "Anything" the above code is called unpacking of sequence, so there must be some variable on left side of assignment operator. but you have list of integers, why? On Tue, Jul 23, 2013 at 11:15 PM, Don Jennings wrote: > > On Jul 21, 2013, at 10:26 PM, Amandeep Behl wrote: > > > > > > > def Move(label): > > label = "Anything" > > > > a_list = [1,2,3] > > Move(a_list) > > > > I don't see any error when executing above but when i manually assign > [1,2,3] = "Anything" i get error > > Why? > > Repeat after me: label is a name, label is a name, label is a name ;>) > > So, you misunderstand what is happening in your code. Your function > accepts the argument named "label", but you do nothing with the object (a > list of numbers in this case). Instead, you use the same name and assign it > to the string object "Anything". > > Assignment works by assigning a name (on the left side of the operator), > to an object on the right side. > > Take care, > Don > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question in regards to loops and matplotlib
So I just started coding, and I'm so glad I chose Python to start me off! I really enjoy the clean layout, easy syntax, and power of the language. I'm doing astronomy research and I just started teaching myself matplotlib along with my general python work. I feel like I'm catching on quick, but I also feel that this particular plot script is a little rough. The plot looks correct, but the code seems really long for what I'm trying to do. So any tricks to make this more efficient would be greatly appreciated! A little bit about what's going on before I post the script. I'm using np.genfromtext to upload a CSV file of a bunch of astronomy data. I need to break this data down into multiple subsets. 4 mass separated subsets (row['logM']) and each of those is divided into bulge and disk dominated. And for each of those I need to separate quiescent and star forming. So I have a total of 8 star forming subsets and 8 quiescent subsets. And all sixteen different styles of object need a distinct marker on the plot. I hope that with the comments you can see where I divided those up in the code. I did it all with a ton of for loops and if statements filling in a bunch of empty arrays. Hopefully this is enough info to make sense of what I'm going for. My main question is can I shorten this code, especially the for loops, to make it more efficient and clean? Here is the script: # -*- coding: utf-8 -*- #- Zach Rizer #- UVJ plot #- data = n>2_qui_flag.csv import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patch from matplotlib.path import Path fig = plt.figure('UVJ') ax = fig.add_subplot(111) #subplot for shaded region ## # - Data uploaded from preliminary TopCat CSV Files data = np.genfromtxt('/Users/ProtonLenny/Documents/Research/Catalog_Data/Catalog_3/n>2_qui_flag.csv',\ dtype=None,names=True,delimiter =",") # - Define Quiesent Subset qui_m1d_xval = [] qui_m1d_yval = [] qui_m2d_xval = [] qui_m2d_yval = [] qui_m3d_xval = [] qui_m3d_yval = [] qui_m4d_xval = [] qui_m4d_yval = [] qui_m1b_xval = [] qui_m1b_yval = [] qui_m2b_xval = [] qui_m2b_yval = [] qui_m3b_xval = [] qui_m3b_yval = [] qui_m4b_xval = [] qui_m4b_yval = [] for row in data: if row['Dv'] > 0.65 and row['DSw'] > 0.65: * # filling disk-dom arrays* if row['UminV'] > 1.3 and row['VminJ'] < 1.6 and row['UminV'] > 0.88*(row['VminJ']+0.59):#quiescent criteria at particular z if row['Z'] >= 0.6 and row['Z'] < 0.9:#redshift bin criteria if row['logM'] >= 9.7 and row['logM'] < 10:#mass subsets for shape in plots qui_m1d_xval.append(row['VminJ']) * # (x) fill the empty list with the data from the appropriate column.* qui_m1d_yval.append(row['UminV']) elif row['logM'] >= 10 and row['logM'] < 10.5: qui_m2d_xval.append(row['VminJ']) qui_m2d_yval.append(row['UminV']) elif row['logM'] >= 10.5 and row['logM'] < 10.8: qui_m3d_xval.append(row['VminJ']) qui_m3d_yval.append(row['UminV']) elif row['logM'] >= 10.8: qui_m4d_xval.append(row['VminJ']) qui_m4d_yval.append(row['UminV']) if row['Dv'] < 0.35 and row['DSw'] > 0.65: * # filling bulge-dom arrays* if row['UminV'] > 1.3 and row['VminJ'] < 1.6 and row['UminV'] > 0.88*(row['VminJ']+0.59):#quiescent criteria at particular z if row['Z'] >= 0.6 and row['Z'] < 0.9:#redshift bin criteria if row['logM'] >= 9.7 and row['logM'] < 10:#mass subsets for shape in plots qui_m1b_xval.append(row['VminJ']) qui_m1b_yval.append(row['UminV']) elif row['logM'] >= 10 and row['logM'] < 10.5: qui_m2b_xval.append(row['VminJ']) qui_m2b_yval.append(row['UminV']) elif row['logM'] >= 10.5 and row['logM'] < 10.8: qui_m3b_xval.append(row['VminJ']) qui_m3b_yval.append(row['UminV']) elif row['logM'] >= 10.8: qui_m4b_xval.append(row['VminJ']) qui_m4b_yval.append(row['UminV']) # - Define Star-Forming Subset sf_m1d_xval = [] sf_m1d_yval = [] sf_m2d_xval = [] sf_m2d_yval = [] sf_m3d_xval = [] sf_m3d_yval = [] sf_m4d_xval = [] sf_m4d_yval = [] sf_m1b_xval = [] sf_m1b_yval = [] sf_m2b_xval = [] sf_m2b_yval = [] sf_m3b_xval = [] sf_m3b_yval = [] sf_m4b_xval = [] sf_m4b_yval = [] for row in data: if row['Dv'] > 0.65 and row['DSw'] > 0.65: # filling disk-dom arrays if row['UminV'] < 1.3 or row['VminJ'] > 1.6 or row['UminV'] < 0.88*(row['VminJ']+0.59):#star forming creteria at particular z if row['Z'] >= 0.6 and row['Z'] < 0.9:#reshift bin criteria if row['logM'] >= 9.7 an
[Tutor] (no subject)
Hello, I am trying to generate a 2D histogram for two arrays of data in CSV format. The code is: x, y = '5k_vec.csv','tcd_5k.csv' H, xedges, yedges = np.histogram2d(x, y) H.shape, xedges.shape, yedges.shape # We can now use the Matplotlib to visualize this 2-dimensional histogram: extent = [yedges[0], yedges[-1], xedges[-1], xedges[0]] import matplotlib.pyplot as plt plt.imshow(H, extent=extent, interpolation='nearest') # plt.colorbar() # plt.show() And the errors I am getting on Wakari are: TypeError Traceback (most recent call last) in () 1 x, y = '5k_vec.csv','tcd_5k.csv'> 2 H, xedges, yedges = np.histogram2d(x, y) 3 H.shape, xedges.shape, yedges.shape 4 5 # We can now use the Matplotlib to visualize this 2-dimensional histogram: /opt/anaconda/envs/np17py27-1.5/lib/python2.7/site-packages/numpy/lib/twodim_base.pyc in histogram2d(x, y, bins, range, normed, weights)609 xedges = yedges = asarray(bins, float)610 bins = [xedges, yedges]--> 611 hist, edges = histogramdd([x,y], bins, range, normed, weights)612 return hist, edges[0], edges[1]613 /opt/anaconda/envs/np17py27-1.5/lib/python2.7/site-packages/numpy/lib/function_base.pyc in histogramdd(sample, bins, range, normed, weights)307 smax = ones(D)308 else:--> 309 smin = atleast_1d(array(sample.min(0), float))310 smax = atleast_1d(array(sample.max(0), float))311 else: /opt/anaconda/envs/np17py27-1.5/lib/python2.7/site-packages/numpy/core/_methods.pyc in _amin(a, axis, out, keepdims) 12 def _amin(a, axis=None, out=None, keepdims=False): 13 return um.minimum.reduce(a, axis=axis,---> 14 out=out, keepdims=keepdims) 15 16 def _sum(a, axis=None, dtype=None, out=None, keepdims=False): TypeError: cannot perform reduce with flexible type Any help would be appreciated! -- *Rocko Brown*, MS, EIT PhD Candidate Department of Land, Air, & Water Resources University of California, Davis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Online references for Python
Hi: I was wondering if anyone could suggest a good quality online resource tool or compendium to provide a beginner's level of information to start learning the Python language. Thank you. Rene Datta reneda...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] adding users to tweets on a list
On 2013-08-06 03:48, Saad Javed wrote: > I want to add users to the tweet from the list, the no. of users added > based on the length of the tweet. It looks like you're using Python 2, but you didn't specify. I'd probably do something like this: #!/usr/bin/env python MAX_LENGTH = 140 users = [ "saad", "asad", "sherry", "danny", "ali", "hasan", "adil", "yousaf", "maria", "bilal", "owais", ] def populate(): message = raw_input("Enter string: ") while users: new_message = " ".join([message, "@" + users.pop(0)]) if len(new_message) > MAX_LENGTH: break message = new_message return message if __name__ == "__main__": print(populate()) pgpOYYsWsbV6Z.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi
Hi, As per your request below, I have attached a stand-alone example (test3d.py) of my problem. I am trying to plot in 3D using ion() from a loop. The code should plot x,y,z coordinates from a loop in ion(). We should see the plot line moving and the marker moving as well. I have also attached a working 2d-plot (test2d.py) to show what it's supposed to do. The 3d plot (test3d.py) should plot the same but with an additional z coordinates and a z axis! Thanks Vick -Original Message- From: Oscar Benjamin [mailto:oscar.j.benja...@gmail.com] Sent: Thursday, 01 August, 2013 01:42 To: Vick Subject: Re: [Tutor] hi On 31 July 2013 22:20, Vick wrote: > Hello, Hi Vick, I would prefer it if you would send questions like this to the tutor mailing list rather than directly to me. This is because: 1) I'm often unable to respond and there are many other people there who could help (I may be the only one there who understands ODEs but I'm certainly not the only one who understands matplotlib). 2) It's helpful for others on the tutor mailing list to see the kind of problems (and solutions) that people new to Python are working with. 3) Any problem/solution gets publicly archived for future reference. > Can you help me please with plotting in 3D using ion()? > > My code is the following: > > from pylab import * > #import pylab > from mpl_toolkits.mplot3d.axes3d import Axes3D import > matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d > > plt.ion() > > fig = plt.figure(dpi=100) > ax = axes3d.Axes3D(fig)#fig.add_subplot(111, projection = '3d') > > > tn= mpf('300')#mpf('800')*dt > > for i in drange (t+dt, tn,dt): > mi = testran(i,mi,dt) > #print i+ dt," ", mi > a.append(mi[0]) > b.append(mi[1]) > z1.append(mi[2]) > c.append(mi[6]) > d.append(mi[7]) > z2.append(mi[8]) > #clf() > ax.plot(a,b,z1)#linestyle='None', marker='o', markersize = 5) > ax.plot(a,b,z1, marker='o', linestyle='None') > ax.plot(c,d,z2) > ax.plot(c,d,z2, marker='o', linestyle='None') > #draw() > > #grid() > #show() > > I'm trying to plot in 3D, coordinates that are appended from a loop > using ion(), but it doesn't plot. I get something different: $ python plot3d.py Traceback (most recent call last): File "plot3d.py", line 13, in tn= mpf('300')#mpf('800')*dt NameError: name 'mpf' is not defined Where does the mpf function come from? There are many other symbols that are not defined (t, dt, testran, ...) so presumably this code is incomplete somehow. Could you please make a complete example illustrating the problem you have and then post it to the tutor list? Oscar from pylab import * import matplotlib.pyplot as plt def drange(start, stop, step): r = start while r < stop: yield r r += step a=[] b=[] z1=[] c=[] d=[] z2=[] plt.ion() fig = plt.figure(dpi=100) ax = fig.add_subplot(111) t = 0 dt = 1 tn= 50 for i in drange (t+dt, tn,dt): aa = sin(i) bb = cos(i) aa1 = 1.5 *sin(i) bb1 = 1.5*cos(i) a.append(aa) b.append(bb) c.append(aa1) d.append(bb1) clf() plot(a,b)#linestyle='None', marker='o', markersize = 5) plot(aa,bb, marker='o', linestyle='None') plot(c,d) plot(aa1,bb1, marker='o', linestyle='None') draw() #grid() #show() from pylab import * #import pylab from mpl_toolkits.mplot3d.axes3d import Axes3D import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d def drange(start, stop, step): r = start while r < stop: yield r r += step a=[] b=[] z1=[] c=[] d=[] z2=[] plt.ion() fig = plt.figure(dpi=100) ax = axes3d.Axes3D(fig)#fig.add_subplot(111, projection = '3d') t = 0 dt = 1 tn= 50 for i in drange (t+dt, tn,dt): aa = sin(i) bb = cos(i) cc = aa*bb aa1 = 1.5 *sin(i) bb1 = 1.5*cos(i) cc1 = aa1*bb1 a.append(aa) b.append(bb) z1.append(cc) c.append(aa1) d.append(bb1) z2.append(cc1) #clf() ax.plot(a,b,z1)#linestyle='None', marker='o', markersize = 5) ax.plot(a,b,z1, marker='o', linestyle='None') ax.plot(c,d,z2) ax.plot(c,d,z2, marker='o', linestyle='None') plt.draw() #grid() #show() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] adding users to tweets on a list
On 2013-08-06 19:42, Chris Down wrote: > All that needs to happen is to move the pop to the top of the MAX_LENGTH > check: > > while len(new_message) + len(add) <= MAX_LENGTH: ...or, better, remove the if...break and just do: while users and len(new_message) + len(add) <= MAX_LENGTH: pgpWu6B0bGjbi.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] .txt matrix import
Hello, This is my first time using Tutor, so I apologize for any fallacies I may be making; my problem involves opening a .txt file which contains several lines of descriptive information followed by a tab delimited matrix of numerical values… I am trying to find an effective way in which to skip the first 'X' number of lines in the .txt file (54 in my case) and input the columns of data into individual arrays (note the 55th line denotes the title of the column, so preferably I would like to have python use those values as the names to the individual array, but I am unsure of how involved that may become) Any hints/suggestions/pointers would be appreciated. Thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] adding users to tweets on a list
On 2013-08-06 14:40, Saad Javed wrote: > It will add max no. of users to one tweet until limit is reached. I want > all users added to the tweet. E.g. if 4 users can be added to the tweet > before reaching the limit, return three tweets...first two with 4 users > attached and the last one with three. Ah, I see. Sorry, I misread your requirements. Something like this should work. #!/usr/bin/env python MAX_LENGTH = 140 class TweetTooLongError(Exception): """ Raised when a user would be too long to add to the tweet, even alone. """ pass def generate_tweets(message, users): """ Generate tweets based around a message, with users appended to each tweet. :param message: the base message :param users: a group of users to append :returns: tweets based around the message to the users """ add = "" longest_in_list = " @" + max(users, key=len) if len(longest_in_list) + len(message) > MAX_LENGTH: raise TweetTooLongError( "At least one user would make the tweet too long." ) while users: new_message = message while len(new_message) + len(add) <= MAX_LENGTH: new_message += add if not users: break add = " @" + users.pop(0) yield new_message if __name__ == "__main__": users = [ "saad", "asad", "sherry", "danny", "ali", "hasan", "adil", "yousaf", "maria", "bilal", "owais", ] message = raw_input("Enter string: ") print("\n".join(generate_tweets(message, users))) pgpCWLSHd9g2t.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] adding users to tweets on a list
On 2013-08-06 22:31, Saad Javed wrote: > Thank you for your response. This code has a bug. > > If there is one user left in the user list, it doesn't print a tweet with > just that one user added. For example use this string: "These are my > friends living in the same city as i am. I have known them for years. They > are good people in general. They are:"...you will see that "owais" is still > in the list and is not added to a new tweet and printed. Good catch, that's my bad, sorry. Because pop() is called on the last element just before the next iteration, when `users' is coerced to a bool, it becomes False in the outer while loop. This affects only 50% of cases because it's possible we will be in the inner loop when we hit the last element in `users', which is why I didn't see it. All that needs to happen is to move the pop to the top of the MAX_LENGTH check: while len(new_message) + len(add) <= MAX_LENGTH: add = " @" + users.pop(0) new_message += add if not users: break pgpJ22_EEMAoB.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] adding users to tweets on a list
On 2013-08-06 22:49, Saad Javed wrote: > That causes: > > Enter string: These are my friends living in the same city as i am. I have > known them for years. They are good people in general. They are: > Traceback (most recent call last): > File "chris_tweet_len.py", line 44, in > print("\n".join(generate_tweets(message, users))) > File "chris_tweet_len.py", line 31, in generate_tweets > while users and len(new_message) + len(add) <= MAX_LENGTH: > UnboundLocalError: local variable 'new_message' referenced before assignment Cannot reproduce. I'm not sure how you edited the script, but somehow you moved new_message to where it is unbound. See attached. > And the earlier fix now adds two users to a tweet, then one user, then two > user, then one... :( I don't see how that differs from your expected output...? > I want all users added to the tweet. E.g. if 4 users can be added to the > tweet before reaching the limit, return three tweets...first two with 4 users > attached and the last one with three. You hit the 140 character limit if another user is added, so it resets to the base message and adds the next user(s) as possible. What is your expected output for that sample input? #!/usr/bin/env python MAX_LENGTH = 140 class TweetTooLongError(Exception): """ Raised when a user would be too long to add to the tweet, even alone. """ pass def generate_tweets(message, users): """ Generate tweets based around a message, with users appended to each tweet. :param message: the base message :param users: a group of users to append :returns: tweets based around the message to the users """ add = "" longest_in_list = " @" + max(users, key=len) if len(longest_in_list) + len(message) > MAX_LENGTH: raise TweetTooLongError( "At least one user would make the tweet too long." ) while users: new_message = message while users and len(new_message) + len(add) <= MAX_LENGTH: add = " @" + users.pop(0) new_message += add yield new_message if __name__ == "__main__": users = [ "saad", "asad", "sherry", "danny", "ali", "hasan", "adil", "yousaf", "maria", "bilal", "owais", ] message = raw_input("Enter string: ") print("\n".join(generate_tweets(message, users))) pgpgSwyxathrA.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] adding users to tweets on a list
On Wednesday, August 7, 2013, Alan Gauld wrote: > On 07/08/13 15:41, Saad Javed wrote: > >> There was only Chris responding >> > > Apparently he didn't CC the list so the rest of us didn't see it(*). > > is that what's confusing? >> > > It's not just the lack of attribution but the fact we just didn't see the > post to which you are replying. > > (*)It is possible that Chris' mail is in the moderation queue, > which I was hoping to visit tonight or tomorrow... > In which case, watch this space... > > Chris has been emailing me directly. Thats why his responses are not showing up in the conversation. Dear Chris, please remember to send your replies to tutor@python.org with the subject of the question ("adding users to tweets on a list"), so that others can see them. Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] adding users to tweets on a list
On Thursday, August 8, 2013, Chris Down wrote: > On 2013-08-08 02:40, Saad Javed wrote: > > Chris has been emailing me directly. Thats why his responses are not > > showing up in the conversation. > > Dear Chris, please remember to send your replies to > > tutor@python.orgwith > > the subject of the question ("adding users to tweets on a list"), so that > > others can see them. > > You are mistaken, python-tutor was Cc'd on every message. I was merely > held in > the moderation queue -- there is nothing I can do about that. > My mistake, I apologize. I did the same thing a while back by accident and assumed you made the same mistake. I guess it must be the moderation queue then. It has reinforced my long standing belief that most programmers are smarter than I am ;) Saad ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] .txt matrix import
Joshua Kim wrote: > Hello, > > This is my first time using Tutor, so I apologize for any fallacies I may be > making; my problem involves opening a .txt file which contains several lines > of descriptive information followed by a tab delimited matrix of numerical > values… I am trying to find an effective way in which to skip the first 'X' > number of lines in the .txt file (54 in my case) and input the columns of > data into individual arrays (note the 55th line denotes the title of the > column, so preferably I would like to have python use those values as the > names to the individual array, but I am unsure of how involved that may > become) > > > Any hints/suggestions/pointers would be appreciated. > First, let me suggest you not send html mail. It basically tripled the size of your message, and many times it will also distort parts of your message, especially when you're including code. Your query basically says you have a file that's in two parts. The first part is to be ignored, and the second part is a simple csv file, complete with column headings. All you need do to skip the first part is to call readline() on the file object X times, something like: for temp in range(X): infile.readline() At this point, the infile object is positioned at the header line of the csv data. You can then use the csv module to successively turn each row of the infile into a dict, with the names being the ones specified in the file. This will give you the data organized by row. I'd recommend you get this much debugged before trying to convert it to columns. BTW you may not need the csv module if your data itself never has a tab in it. The place where the module really helps is (for example in a comma-delimited file) when there's sometimes a comma in the actual data that needs escaping, or quoting. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Converting a string to an integer
On 31 July 2013 16:14, Art Bullentini wrote: > I'm trying to convert from a string of digits such as x = [y:y+1] into an > integer using int(x). the book says I can do this, but I get an error > message saying no can do. Anybody tell me what's going on? > > Please supply the actual code you've tried and the actual error message please. Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Trouble, Please Help!
Hi, On 25 July 2013 00:23, Jonathan Hong wrote: > Hello, > > I am currently working with the Python programming language and had a very > basic question regarding the start up of Python. For some reason, when I > open up the Command Prompt in my Windows 7 computer, I am unable to access > python files. > I'd like to add the following suggestion to the link Antonio's already sent you: http://www.voidspace.org.uk/python/articles/command_line.shtml Regards, Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone explain this
Amandeep Behl wrote: > Can anyone explain this code below: > > > > Can anyone explain this code > below:import sysimport > os if __name__ == > '__main__': sys.path.insert(0, "..") > else: sys.path.insert(0, > os.path.join( os.path.split(__file__)[0], > '..')) > Yes, the gobbledygook is caused by selecting html email, rather than the needed text form. As for the code that's buried inside there, it seems to have no usefulness if the file is run directly as a script, but if it's imported from another script, it adds a particular directory to the search path. Subsequent imports may find imports in that directory. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone explain this
On Fri, Aug 2, 2013 at 4:33 PM, Amandeep Behl wrote: > Can anyone explain this code below: > > > import sys > import os > > if __name__ == '__main__': > sys.path.insert(0, "..") > else: > sys.path.insert(0, os.path.join( > os.path.split(__file__)[0], '..')) > When you run this module as a standalone, the value of __name__ will be "__main__"; this is a standard test to see whether you're running it from the command line or importing it from another script. If you're running this code standalone, it will insert the directory one level up from the current working directory (..) as the first item in the Python path, so that subsequent imports will look there first. If you're calling this code from another script, it can't rely on knowing the current working directory - so it calls os.path.split to find the directory where this file is located; then it inserts the parent of that directory as the first item in the Python path. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] inconsistent destruction
On Wed, Aug 07, 2013 at 08:54:26PM -0700, Jim Mooney wrote: > This bugs me for some reason. The final variable is saved in a for > loop but not in a list comprehension. It just seems to me they should > both be destroyed to avoid confusion. The variable in a for-loop is deemed to be in the same scope as the rest of the function, the same as any other local variable. This is often very useful: for item in objects: if condition(item): break print(item) If for-loops introduced their own scope, as they do in a few other languages, you would need to do something like this: found = None for item in objects: if condition(item): found = item break print(found) On the other hand, list comprehensions (since Python 3) and generator expressions (always) are deemed to exist in their own scope. That makes conceptual sense, since a generator expression is its own chunk of executable code, like a function, and in fact are implemented much the same way that functions are implemented internally. List comps look the same, and since Python 3 are now treated the same. That way you can use a list comp or generator expression without worrying that its loop variable will clobber an existing local variable of the same name. [...] > Is there a form of for loop that would destroy the loop variable? I > could always do del cnt right after the for, but that seems > artificial. Why do you care? The typical function is chock full of local variables that are used a few times, then hang around doing nothing until the function exits. This doesn't cause any problems in practice. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor