Re: [Tutor] Error Checking/Defensive Programming

2012-01-26 Thread Peter Otten
Modulok wrote:

> if number <= 10 and number >= 1:

I like that you can spell that

if 1 <= number <= 10:

in Python. 


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] TypeError: only length-1 arrays can be converted to Python scalars

2012-01-26 Thread stm atoc
Hi,

I have a question regarding the TypeError.

I have this script as follows in Python. I have run a program in Fortran:

# coding: utf-8
from pylab import *
import numpy
import matplotlib.pyplot as pyplot
import matplotlib.mlab as mlab

t=3600
N = 100
dz = 1.0

with open("act_out.list", "r") as f:
   z = numpy.array([float(v) for v in f.readline().split()[1:]])
zm = z*1.0e6

a = numpy.loadtxt("act_out.list", skiprows=3)
t=a[:,0]
nu = a[0:,1:N+1]
Conc = a[:, N+1:]
hsml=zeros((103))
cprof=zeros((103))

hsml[0]=-1300.
hsml[-2]=-300.
hsml[-1]=0.
hsml[1:-2]=z*100-300.

cprof[0]=50.
cprof[-2]=500.
cprof[-1]=500.

idx=int(where(t==1800)[0])
cprof[1:-2]=Conc[idx]

lw = 2.0
dpi = 80
figure(figsize=(8,8),dpi=dpi)
pyplot.plot(cprof,hsml,'r-')

pyplot.xlabel('$Conc, mmol C m^3$')
pyplot.ylabel('$Hsml, micrometer$')
pyplot.grid(True)

legend()
savefig('Conc.png')
show()

after runing Python, I hav ethis massage:

 TypeError: only length-1 arrays can be converted to Python scalars

Any suggestion?  in fact, what I missed and what I should add to have
a right result!

Thanks in advance,
Sue
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] TypeError: only length-1 arrays can be converted to Python scalars

2012-01-26 Thread Peter Otten
stm atoc wrote:

> Hi,
> 
> I have a question regarding the TypeError.
> 
> I have this script as follows in Python. I have run a program in Fortran:
> 
> # coding: utf-8
> from pylab import *
> import numpy
> import matplotlib.pyplot as pyplot
> import matplotlib.mlab as mlab
> 
> t=3600
> N = 100
> dz = 1.0
> 
> with open("act_out.list", "r") as f:
>z = numpy.array([float(v) for v in f.readline().split()[1:]])
> zm = z*1.0e6
> 
> a = numpy.loadtxt("act_out.list", skiprows=3)
> t=a[:,0]
> nu = a[0:,1:N+1]
> Conc = a[:, N+1:]
> hsml=zeros((103))
> cprof=zeros((103))
> 
> hsml[0]=-1300.
> hsml[-2]=-300.
> hsml[-1]=0.
> hsml[1:-2]=z*100-300.
> 
> cprof[0]=50.
> cprof[-2]=500.
> cprof[-1]=500.
> 
> idx=int(where(t==1800)[0])
> cprof[1:-2]=Conc[idx]
> 
> lw = 2.0
> dpi = 80
> figure(figsize=(8,8),dpi=dpi)
> pyplot.plot(cprof,hsml,'r-')
> 
> pyplot.xlabel('$Conc, mmol C m^3$')
> pyplot.ylabel('$Hsml, micrometer$')
> pyplot.grid(True)
> 
> legend()
> savefig('Conc.png')
> show()
> 
> after runing Python, I hav ethis massage:
> 
>  TypeError: only length-1 arrays can be converted to Python scalars
> 
> Any suggestion?  in fact, what I missed and what I should add to have
> a right result!

By retyping the error message or omitting the traceback you are stripping 
off information that is valuable for debugging your problem. Always cut and 
paste the complete traceback.
Also, I cannot run your script as it relies upon data that you don't 
provide. Again, debugging becomes easier if you make your script self-
contained, e. g. set 'a' to some value explicitly with

a = numpy.array([...])

Anyway, here's my guess:

The t array has more than one 1800 entry:

>>> t = numpy.array([1., 1800., 1800.])
>>> numpy.where(t==1)
(array([0]),)
>>> int(numpy.where(t==1)[0])
0
>>> int(numpy.where(t==1800)[0])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: only length-1 arrays can be converted to Python scalars

I don't know what you are trying to do; if you are content with the index of 
the first occurrence of 1800 and are sure there is always at least one you 
could write

idx = numpy.where(t==1800)[0][0]


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Socket Programming

2012-01-26 Thread Navneet

Hi,

I am trying to create a chat program.(Programs are attached)
Please find the code below, where I am having the problem.

def run( self ):
while 1:
print "Hello There "
print self.descriptors
# Await an event on a readable socket descriptor
(sread, swrite, sexc) = select.select( self.descriptors, 
[], [] )

print sexc
# Iterate through the tagged read descriptors
print sread
print "Hello There 1 "
for sock in sread:


For this I am getting the output as below:
bash-3.1$ python Server.py
Enter the Port:...9009
ChatServer started on port 9009
Hello There 
[]


But it is not printing the value of sread or "Hello There 1 !"





import socket
import select


class ChatServer:
def __init__( self, port ):
self.port = port;
self.srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
self.srvsock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
self.srvsock.bind( ("", port) )
self.srvsock.listen( 5 )
self.descriptors = [self.srvsock]
print 'ChatServer started on port %s' % port
def run( self ):
while 1:
print "Hello There "
print self.descriptors
# Await an event on a readable socket descriptor
(sread, swrite, sexc) = select.select( self.descriptors, [], [] )
print sexc 
# Iterate through the tagged read descriptors
print sread
print "Hello There 1 "
for sock in sread:
# Received a connect to the server (listening) socket
if sock == self.srvsock:
self.accept_new_connection()
else:
# Received something on a client socket
str = sock.recv(100)
# Check to see if the peer socket closed
if str == '':
host,port = sock.getpeername()
str = 'Client left %s:%s\r\n' % (host, port)
self.broadcast_string( str, sock )
sock.close()
self.descriptors.remove(sock)
else:
host,port = sock.getpeername()
newstr = '[%s:%s] %s' % (host, port, str)
self.broadcast_string( newstr, self.srvsock )

def accept_new_connection( self ):
newsock, (remhost, remport) = self.srvsock.accept()
self.descriptors.append( newsock )
newsock.send("You're connected to the Python chatserver\r\n")
str = 'Client joined %s:%s\r\n' % (remhost, remport)
self.broadcast_string( str, newsock )

def broadcast_string( self, str, omit_sock ):
for sock in self.descriptors:
if sock != self.srvsock and sock != omit_sock:
sock.send(str)
print str,

if __name__ == '__main__':

portno = int(raw_input("Enter the Port:..."))
s = ChatServer(portno)
s.run()

from Tkinter import *
import tkMessageBox
import socket
import logging
import sys, time
import pickle
import thread



class ClientChat():
def __init__(self,serverport):
self.counter = 0

self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.host = 'localhost' # server address
self.port = serverport # server port 

# connect to server
self.s.connect((self.host, self.port))

self.chatclient = Tk()

self.chatclient["padx"] = 200
self.chatclient["pady"] = 200

self.chatclient.title("Client")

self.f1 = Frame(self.chatclient,width = 100, height = 10)
self.f1.pack(side = TOP)

self.f2 = Frame(self.chatclient,width = 100, height = 10)
self.f2.pack(side = BOTTOM)


self.recvmsg = Text(self.f1, width = 100, height = 10)
self.sb = Scrollbar(self.f1)
self.sb.pack(side = RIGHT, fill = Y)

self.sb.config(command = self.recvmsg.yview)
self.recvmsg.config(yscrollcommand=self.sb.set)
self.recvmsg.pack(padx = 10, pady =10)

self.sendmsg = Text(self.f2, width = 100, height = 5)
self.sendmsg.pack(padx = 10, pady =20)

self.sendbutton =Button(self.f2, width = 5, height = 2, text = "Send", 
command = self.senddata)
self.sendbutton.pack(side = LEFT, padx = 10, pady = 10)

self.sendbutton =Button(self.f2, width = 5, height = 2, text = "Exit", 
command = self.exitchat)
self.sendbutton.pack(side = RIGHT, padx = 10, pady = 10)

self.chatclient.mainloop()


def senddata(self):
self.k = self.sendmsg.get(1.0, END)
self.sendmsg.delete(1.0, END)
self.s.send(self.k)

if self.counter == 0:
thread.start_new_thread(self.recvdata,())
##if self.k == '':
##   

[Tutor] splitting the large file into small pieces and download

2012-01-26 Thread Arun Kumar
Hi all,

I want to build a small download accelerator program. I want to know how to
split the file to be downloaded into small pieces and assign the each small
piece to a thread for downloading.
-- 
Thanks & Regards,

Arun Kumar
http://clicknscroll.blogspot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Pythonic way of concatenation of elements in an array

2012-01-26 Thread spawgi
Hello,

My code is -

l = len(m)
item = str(m[1])
for i in range(2,l):
item = item + "-" + str(m[i])

This code is part of a bigger function. It works fine. But I am not happy
with the way I have written it. I think there is a better (Pythonic) way to
rewrite it.
If anyone knows how to improve this snippet, I would be very thankful.

Thanks and Regards,
Sumod


-- 
http://spawgi.wordpress.com
We can do it and do it better.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pythonic way of concatenation of elements in an array

2012-01-26 Thread Steven D'Aprano

spa...@gmail.com wrote:

Hello,

My code is -

l = len(m)
item = str(m[1])
for i in range(2,l):
item = item + "-" + str(m[i])

This code is part of a bigger function. It works fine. But I am not happy
with the way I have written it. I think there is a better (Pythonic) way to
rewrite it.
If anyone knows how to improve this snippet, I would be very thankful.


(1) Never use "l" as a variable name, as it looks too much like 1.


(2) Use meaningful names. When posting snippets for help, you should show 
example data.



(3) You almost never need to iterate over an index by hand. Instead iterate 
over the items themselves. That is, instead of this:


for i in len(sequence):
do_something_with( sequence[i] )

do this instead:

for item in sequence:
do_something_with( item )


and similar variations.


(4) When you want only part of a sequence, use slicing to extract just the 
parts you care about.



(5) When assembling strings from substrings, never use repeated concatenation 
using + as that can be EXTREMELY slow. Use str.join to build the string in one 
assignment, instead of multiple assignments.


Your code shown above is *very* inefficient and will be PAINFULLY slow if m is 
very large. To understand why, you should read this article:


http://www.joelonsoftware.com/articles/fog000319.html

In this case, you can replace your snippet with this:

result = '-'.join(str(item) for item in m[1:])



For example:

py> m = [1, 2, "hello world", (23, 42), 5]
py> '-'.join(str(item) for item in m[1:])
'2-hello world-(23, 42)-5'



--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] splitting the large file into small pieces and download

2012-01-26 Thread Walter Prins
Hi Arun,

On 26 January 2012 21:27, Arun Kumar  wrote:
> I want to build a small download accelerator program. I want to know how to
> split the file to be downloaded into small pieces and assign the each small
> piece to a thread for downloading.

OK, so what else have you tried and what are you having problems with?
 Or have you just come up with that requirement spec and nothing else?
 While we're not going to write your program for you, we'd be willing
to help you with specific problems you may be stuck on.  I'd like to
add: This is not strictly speaking a Python language/tutoring
question, and really more of a general internet programming question,
so you may be better off asking elsewhere, such as (perhaps)
http://stackoverflow.com/

Some other questions: Do you understand websites and http traffic and
how to do this with Python well enough to download files directly
(without splitting them up) already? Do you understand threads and how
to use them already?   Obviously these 2 things are neccesary (though
not sufficient) conditions for you to be able to have a chance at
writing your program.

HTH,

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Why do you have to close files?

2012-01-26 Thread amt
Exercise 17, extra credit 6 Learn python the hard way: Find out why
you had to do output.close() in the code.


Code:
from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)


input = open(from_file)
indata = input.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

output = open(to_file, 'w')
output.write(indata)

print "Alright, all done."

output.close()
input.close()


I don't get it. If you don't close input and output it works exactly
the same as if you would close them, so why do you have to do
output.close() and input.close()?

Also does it matter if you do: input.close() and then output.close()?
Is there an order to follow?



Thanks in advance, amt.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why do you have to close files?

2012-01-26 Thread ian douglas

On 1/26/12 3:20 PM, amt wrote:

Exercise 17, extra credit 6 Learn python the hard way: Find out why
you had to do output.close() in the code.


Code:

output.close()
input.close()


I don't get it. If you don't close input and output it works exactly
the same as if you would close them, so why do you have to do
output.close() and input.close()?

Also does it matter if you do: input.close() and then output.close()?
Is there an order to follow?

There's no order to follow, and it's really more about cleaning up after 
yourself than being a necessity. If you were writing to real files, your 
operating system would limit how many open files you could have at any 
time, so you want to make sure you close file handles you're no longer 
using.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why do you have to close files?

2012-01-26 Thread Andre' Walker-Loud
>> Exercise 17, extra credit 6 Learn python the hard way: Find out why
>> you had to do output.close() in the code.
>> 
>> 
>> Code:
>> 
>> output.close()
>> input.close()
>> 
>> 
>> I don't get it. If you don't close input and output it works exactly
>> the same as if you would close them, so why do you have to do
>> output.close() and input.close()?
>> 
>> Also does it matter if you do: input.close() and then output.close()?
>> Is there an order to follow?
>> 
> There's no order to follow, and it's really more about cleaning up after 
> yourself than being a necessity. If you were writing to real files, your 
> operating system would limit how many open files you could have at any time, 
> so you want to make sure you close file handles you're no longer using.

Also - from experience, output.close() can be very important.

eg. - I often use python to
1- create an initialization file
2 - use this initialization file with some executable code

These are steps I perform in the same script.  One time, I forgot to do 
"output.close()" before handing my file to the executable.  Then for two weeks, 
I was wondering what was wrong with my code?!?  It compiled damn it, and if I 
ran my job (this is on a big computing cluster) in interactive mode, everything 
worked!?!  What was going wrong?  a

Well, when I finally realized I forgot to "close()" my file, I felt rather 
silly.

The problem is python does not actually write the file to disk until you 
execute "output.close()".  When you end your session, if you forgot to do 
"output.close()" it will write it to disk for you (it has all the time for me 
at least).  But in my case, it was the same python "session" in which I was 
trying to both write the file, and then use it.


Andre

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why do you have to close files?

2012-01-26 Thread Dave Angel

On 01/26/2012 06:20 PM, amt wrote:

Exercise 17, extra credit 6 Learn python the hard way: Find out why
you had to do output.close() in the code.


Code:
from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)


input = open(from_file)
indata = input.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

output = open(to_file, 'w')
output.write(indata)

print "Alright, all done."

output.close()
input.close()


I don't get it. If you don't close input and output it works exactly
the same as if you would close them, so why do you have to do
output.close() and input.close()?

Also does it matter if you do: input.close() and then output.close()?
Is there an order to follow?


This is an extra credit question, after all.  So it must be a little 
subtle, and it is.


First, Python (the language) does not promise that it will close the 
files for you. The operating system does, when the program exits.  In 
this trivial program, that's right away.  But if your program does 
something else for a while, or repeats this sequence of steps dozens of 
times, you could run out of resources, or overwrite something.


CPython, the most common implementation, does promise that the file will 
be closed when the usage count of the file object goes away.  So if you 
did any of the following, it would close the file:


   1) del output
2) output = None
   3) output = open(someother_file, "w")

However, that's an optimization within CPython, and not necessarily 
guaranteed for other Python implementations, like IronPython or Jython.


Second, some operating system platforms won't let the same file be 
simultaneously open for readonly and for write.  So if the two filenames 
happened to be the same file (through symlink or other mechanism, or 
even using two different ways to describe the same file), you might get 
an error trying to write without having closed the input file.


Try putting the same name for both input and output file, see what it 
does.  Or use an absolute path for the input filename and a relative 
path to the same place for the output file.


The place to close the input file is right after you're done reading the 
data, and before opening the output file.



--

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why do you have to close files?

2012-01-26 Thread Steven D'Aprano

amt wrote:


I don't get it. If you don't close input and output it works exactly
the same as if you would close them, so why do you have to do
output.close() and input.close()?


(1) It is a matter of good programming practice. If you don't close them 
yourself, Python will eventually close them for you. In some versions of 
Python, that might be the instant they are no longer being used; in others, it 
might not happen for a long time. Under some circumstances, it might not 
happen at all.


(2) When writing to a file, the data may not be written to disk until the file 
is closed. When you say "output.write(...)", the data is often cached in 
memory and doesn't hit the hard drive until the file is closed[1]. The longer 
you keep the file open, the greater the chance that you will lose data.


(3) Since your operating system has strict limits on how many file handles can 
be kept open at any one instant, it is best to get into the habit of closing 
them when they aren't needed and not wait for "maid service" to clean up after 
you.


(4) Also, some operating systems (Windows, in particular) treat open files as 
locked and private. While you have a file open, no other program can also open 
it, even just to read the data. This spoils backup programs, anti-virus 
scanners, etc.




Also does it matter if you do: input.close() and then output.close()?
Is there an order to follow?


It makes no real difference, but I prefer to close output files first, so they 
get written to disk a microsecond sooner than they otherwise would have.




[1] Annoyingly, modern hard drives often themselves have their own internal 
memory cache, so even when the operating system flushes data to the disk, 
there is no guarantee that the data will have actually been written to the 
disk platter. But there's nothing really you can do about that except hope 
that the power doesn't go out in the middle of writing to disk!



--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question regarding setup.py

2012-01-26 Thread sp6

Hi All,

I had a question regarding installing packages that I posted a couple  
of days ago. But I'm re-sending the question again.. this time with  
output so that it is clearer.


I am unable to install libraries using 'python setup.py install'

Say that I'm installing a package "kando". I extract it and I'm  
currently in its directory:


Output to dir:
dir
  11357Aug 12 20:43:46 2011  COPYING.txt
   2769Aug 12 20:46:34 2011  PKG-INFO
   1490Aug 12 20:39:31 2011  README.txt
 56Aug 05 20:06:46 2011  kando
   6362Aug 12 20:35:23 2011  kando.py
868Oct 20 17:48:00 2011  setup.py

Next, I try and install kando and this is what I get:

python setup.py install
file kando.py (for module kando) not found
file kando.py (for module kando) not found
error: file '/var/sysmgr/vsh/kando' does not exist
Thu Oct 20 18:35:01 UTC 2011
running install
running build
running build_py
running build_scripts

I guess the installer is not looking in the right path for the files  
to be installed as it cannot find kando.py although I can see it in  
the output of dir. This is not specific to just kando. I have tried  
installing arithmetic-0.5 and other packages.

Can you please tell me how I can change the search path of the installer?
Thanks in advance.

Thanks,
San

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why do you have to close files?

2012-01-26 Thread Alan Gauld

On 26/01/12 23:20, amt wrote:


input = open(from_file)
indata = input.read()
 ...

output = open(to_file, 'w')
output.write(indata)

print "Alright, all done."

output.close()
input.close()


I don't get it. If you don't close input and output it works exactly
the same as if you would close them, so why do you have to do
output.close() and input.close()?


In this case it will work the same 99.9% of the time because when your 
program closes Python will kill all the file objects that you created 
and in the process the files will get written to the disk. However, to 
understand why you need to call close() in the general case you need to 
understand that when you do a write to a file the OS does not 
immediately write the data to the disk (it would be too slow). Instead 
it writes it to a holding area in memory (called a buffer) and then, 
every so often, it copies the buffer out to the real file. When you call 
close() one of the things that happens is that the buffer gets told to 
write to disk, even if it's not full yet. If you don't call close you 
can wind up with data missing from the end of your files.


The other thing that close does is releases the memory and other OS 
resources that are allocated to the file when you open it. Depending on 
the OS there may be limits to how many files can be open at once. Also 
the file may be locked until it is closed preventing other programs from 
accessing it. So in general, whenever you finish using a file, you 
should close it as a good habit... In fact it's a good idea to use a 
try/finally construct to guarantee that the file gets closed, especially 
if you are writing to it:


try:
   foo = open(myFiule,'w')
   # do stuff to foo
finally:
   foo.close()

The only exception to this is if you open the file like this:

with open(myfile) as aFile:
 # use aFile

This construct specifically guarantees to close the file for you at the 
end of the block.


It's one of those things that catches beginners out regularly because 
nine times out of ten not closing the file will seem to work fine then, 
once in a while, it fails and data gets corrupted.


--
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] Pythonic way of concatenation of elements in an array

2012-01-26 Thread spawgi
Hello Steven,

Thanks a lot for the detailed answer. I will implement your suggestions.
Really appreciate it.

Thanks and Regards,
Sumod

On Fri, Jan 27, 2012 at 4:34 AM, Steven D'Aprano wrote:

> spa...@gmail.com wrote:
>
>> Hello,
>>
>> My code is -
>>
>> l = len(m)
>> item = str(m[1])
>> for i in range(2,l):
>>item = item + "-" + str(m[i])
>>
>> This code is part of a bigger function. It works fine. But I am not happy
>> with the way I have written it. I think there is a better (Pythonic) way
>> to
>> rewrite it.
>> If anyone knows how to improve this snippet, I would be very thankful.
>>
>
> (1) Never use "l" as a variable name, as it looks too much like 1.
>
>
> (2) Use meaningful names. When posting snippets for help, you should show
> example data.
>
>
> (3) You almost never need to iterate over an index by hand. Instead
> iterate over the items themselves. That is, instead of this:
>
> for i in len(sequence):
>do_something_with( sequence[i] )
>
> do this instead:
>
> for item in sequence:
>do_something_with( item )
>
>
> and similar variations.
>
>
> (4) When you want only part of a sequence, use slicing to extract just the
> parts you care about.
>
>
> (5) When assembling strings from substrings, never use repeated
> concatenation using + as that can be EXTREMELY slow. Use str.join to build
> the string in one assignment, instead of multiple assignments.
>
> Your code shown above is *very* inefficient and will be PAINFULLY slow if
> m is very large. To understand why, you should read this article:
>
> http://www.joelonsoftware.com/**articles/fog000319.html
>
> In this case, you can replace your snippet with this:
>
> result = '-'.join(str(item) for item in m[1:])
>
>
>
> For example:
>
> py> m = [1, 2, "hello world", (23, 42), 5]
> py> '-'.join(str(item) for item in m[1:])
> '2-hello world-(23, 42)-5'
>
>
>
> --
> Steven
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>



-- 
http://spawgi.wordpress.com
We can do it and do it better.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pythonic way of concatenation of elements in an array

2012-01-26 Thread Andre' Walker-Loud
Hi Steven,

> (5) When assembling strings from substrings, never use repeated concatenation 
> using + as that can be EXTREMELY slow. Use str.join to build the string in 
> one assignment, instead of multiple assignments.
> 
> Your code shown above is *very* inefficient and will be PAINFULLY slow if m 
> is very large. To understand why, you should read this article:
> 
> http://www.joelonsoftware.com/articles/fog000319.html
> 
> In this case, you can replace your snippet with this:
> 
> result = '-'.join(str(item) for item in m[1:])

This was an interesting article.  I have only had one programming class, and 
that was 15 years ago or so, so these are not issues I am aware of.

I often find myself joining strings (and have mostly used + to do it).  An 
alternate method I use is, for eg.

>print('here is a string %s which has many variables %s %s %s I have to sort 
>out' %(s1,s2,s3,s4))

where the various strings (s1 - s4) have been determined elsewhere, perhaps in 
a loop.

Is this method any better at combining strings than the +?  My first guess 
would be no, but that is really just a guess.


Thanks,

Andre
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why do you have to close files?

2012-01-26 Thread Stefan Behnel
Alan Gauld, 27.01.2012 02:16:
> with open(myfile) as aFile:
>  # use aFile

I should add that this is the shortest, safest (as in "hard to get wrong")
and most readable way to open and close a file. It's worth getting used to.

Stefan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor