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

2012-01-27 Thread Blockheads Oi Oi

On 27/01/2012 06:44, Andre' Walker-Loud wrote:

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



You might like to take a look here 
http://wiki.python.org/moin/PythonSpeed/PerformanceTips#String_Concatenation

--
Cheers.

Mark Lawrence.

___
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-27 Thread Alan Gauld

On 27/01/12 06:44, Andre' Walker-Loud wrote:

...  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).


String addition is OK in some languages, or at least better than in 
Python so it is not a universal rule of programming. In Python the big 
problem is that each addition operation creates a new string so Python 
spends a lot of time allocating bigger and bigger chunks of memory only 
to throw it away again.



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

...
Is this method any better at combining strings than the +?


It is quite a bit better because Python can pre-calculate how much 
memory is needed and do it once.


However, I wouldn't get too stressed on speed. String formatting has a 
lot of other advantages over join() and is fast enough most of the time.
I tend to use formatting more than join() in my own code, but join() is 
best if you are building up a string in a loop say. You can append the 
substrings to a list and then join the list at the end.


--
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] Question regarding setup.py

2012-01-27 Thread Evert Rol
> 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 assume you're running this in the unpacked directory (it's what you suggest, 
but I can't tell with 100% certainty.).
Then I can only think that the setup.py is misbehaving; the 
'/var/sysmgr/vsh/kando' mention suggests that. 
Usually, certainly for small libraries (this seems to be one), these are 
relatively small, so perhaps you can post it?
Also, check the README file for any installation suggestions.

Alternatively, if the contents of the kando/ directory just contains Python 
files, you could copy-paste that whole directory into your Python library 
installation directory. The latter is system dependent, but should be 
relatively easy to find out. 

Another thing I can think of that may cause problems, is that in the unpacked 
directory, there is both a kando directory (which presumably contains an 
__init__.py file) and a kando.py file.


> 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?

No, that's not how it works.
You just run python setup.py install in the directory, and Python will happily 
install the library correctly.
You can alter the *installation* path, using a flag like --prefix. Usually, I 
wouldn't recommend that.

  Evert

> Thanks in advance.
> 
> Thanks,
> San
> 
> ___
> 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] compile time calculator

2012-01-27 Thread Surya K

Hi,
I want to calculate compile time for my puzzles. Although I read about 
timeit(), I didn't really understand how it should be applied it.So, can anyone 
write a function for me please!!
I am looking for a function which should solve my puzzle and also show compile 
time. (Later, I should be able to delete that function before submitting my 
code)
The following way is what I am exactly looking at:
define a compile time function such that it should take all my puzzle code and 
provide compile time for it.
(I think timeit() should be called at each statement, which is not flexible, 
don't know exactly.)
can anyone write a program for me? please...
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] compile time calculator

2012-01-27 Thread Blockheads Oi Oi

On 27/01/2012 15:46, Surya K wrote:

Hi,

I want to calculate compile time for my puzzles. Although I read about
timeit(), I didn't really understand how it should be applied it.
So, can anyone write a function for me please!!

I am looking for a function which should solve my puzzle and also show
compile time. (Later, I should be able to delete that function before
submitting my code)

The following way is what I am exactly looking at:

define a compile time function such that it should take all my puzzle
code and provide compile time for it.

(I think timeit() should be called at each statement, which is not
flexible, don't know exactly.)

can anyone write a program for me? please...


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


Nobody will write code for you unless you show that you've made an 
attempt yourself.  Perhaps you're looking for the standard profile 
module?  Or trying optimization prematurely?  Or what?  Please give more 
information about the precise nature of your problem and you will get 
many very useful answers.


--
Cheers.

Mark Lawrence.

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


Re: [Tutor] compile time calculator

2012-01-27 Thread Alan Gauld

On 27/01/12 15:46, Surya K wrote:


I want to calculate compile time for my puzzles.


I'm pretty sure from what follows you don't!
But just to be clear, compile time is the time Python spends converting 
your modules into .pyc files the first time they are imported after a 
change. Why you would want to time that I have no idea, and assume you 
don't really.



 Although I read about timeit(),


timeit is used to measure *execution* times, it has nothing to do with 
compile times.


However, if you want to measure how long your code takes to run then it 
is relevant. Search the archive of this list for some good examples of 
using timeit. I seem to recall Steven wrote an excellent tutorial a few 
months ago.



I am looking for a function which should solve my puzzle and also show
compile time. (Later, I should be able to delete that function before
submitting my code)


I'm afraid you'll need to solve the puzzle yourself. There is unlikely 
to be a ready made one lying around and folks on this list can help but 
we do not do your work for you. (And in this case couldn't since we 
don't know what your puzzle is! Or are you still talking about the Lucky 
numbers one from earlier?)



define a compile time function such that it should take all my puzzle
code and provide compile time for it.

(I think timeit() should be called at each statement, which is not
flexible, don't know exactly.)


Assuming you want run time not compile time you should probably look at 
the Python profiler - in the profile module. It's not totally intuitive 
to set up but the documents give examples. But it doesn't work at the 
line level but at functions.


But if you are still battling with the Lucky Number thing you really 
need to go back to the math, not the Python code. You need a new 
algorithm not tighter code. Wikipedia and Google might be more help than 
the profiler!


--
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] Socket Programming

2012-01-27 Thread Navneet

On 1/26/2012 4:22 PM, Navneet wrote:

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 !"






Hello All,

One more thing I want to add here is, I am trying to create the GUI 
based chat server.(Attached the programs.)

The concept is something like this:
I will start a server on a particular port and different Clients can 
interact with each other using that (more like a chat room )
Now I want to add the GUI part in a different module and want to call 
that module from client program.

But while executing the client1.py I am getting below error :



bash-3.1$ python Client1.py
Enter the server address:...9009
Traceback (most recent call last):
  File "Client1.py", line 53, in 
c = ClientChat(serverport)
  File "Client1.py", line 24, in __init__
gui.callGui()
  File "a:\FedEx\Exp\ClientGui.py", line 37, in callGui
sendbutton =Button(f2, width = 5, height = 2, text = "Send", 
command = C.ClientChat.senddata())
TypeError: unbound method senddata() must be called with ClientChat 
instance as first argument (got nothing instead)













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



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))

gui.callGui()


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

if self.counter == 0:
thread.start_new_thread(self.recvdata,())
##if self.k == '':
##thread.exit()
##self.s.close()
##self.chatclient.destroy()

def exitchat():
self.s.close()
self.chatclient.destroy()

def recvdata(self):
while 1:
self.v = self.s.recv(1024) 
gui.callGui.recvmsg.insert(END,self.v)



if __name__ == '__main__':

serverport = int(raw_input("Enter the server address:..."))
c = ClientChat(serverport)


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


def callGui():
chatclient = Tk()

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

chatclient.title("Client")

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

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


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

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

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

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

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

chatclient.mainloop()
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( ("localhost", port) )
self.srvsock.listen( 5 )
self.descriptors = [self.srvsock]
print 'ChatServer started on port %s' % port
def run( self ):
while 1:
# Await an event on a readable socket descriptor
sread, swrite, sexc = select.select( self.descriptors, [], [],5 )
# Iterate through the tagged read descriptors
for sock in sread:
# Received a connect to the server (listening) socket
if sock == self.srvsock:
self.accept_new_connection()
else:
# Received

Re: [Tutor] compile time calculator

2012-01-27 Thread Steven D'Aprano

Surya K wrote:


can anyone write a program for me? please...



Certainly. My rate is AUD$80 per hour. Please write to me privately to discuss 
financial arrangements.




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


Re: [Tutor] Socket Programming

2012-01-27 Thread Steven D'Aprano

Navneet wrote:

One more thing I want to add here is, I am trying to create the GUI 
based chat server.(Attached the programs.)



Please do not send large chunks of code like this, unless asked. Instead, you 
should try to produce a minimal example that demonstrates the problem. It 
should be:


* short (avoid code which has nothing to do with the problem)

* self-contained (other people must be able to run it)

* correct (it must actually fail in the way you say it fails)

See here for more: http://sscce.org/


In cutting your code down to a minimal example, 9 times out of 10 you will 
solve your problem yourself, and learn something in the process.




bash-3.1$ python Client1.py
Enter the server address:...9009
Traceback (most recent call last):
  File "Client1.py", line 53, in 
c = ClientChat(serverport)
  File "Client1.py", line 24, in __init__
gui.callGui()
  File "a:\FedEx\Exp\ClientGui.py", line 37, in callGui
sendbutton =Button(f2, width = 5, height = 2, text = "Send", command 
= C.ClientChat.senddata())
TypeError: unbound method senddata() must be called with ClientChat 
instance as first argument (got nothing instead)



This one is easy. You need to initialize a ClientChat instance first. This may 
be as simple as:


command = C.ClientChat().senddata

although I'm not sure if ClientChat requires any arguments.

Note that you call the ClientChat class, to create an instance, but you DON'T 
call the senddata method, since you want to pass the method itself as a 
callback function. The button will call it for you, when needed.




--
Steven

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


[Tutor] ignoring certain lines while reading through CSV

2012-01-27 Thread Abhishek Pratap
Hi Guys

I am wondering if there is a keyword to ignore certain lines ( for eg
lines starting with # ) when I am reading them through stl module csv.

Example code:

input_file = sys.argv[1]
csv.register_dialect('multiplex_info',delimiter=' ')

with open(input_file, 'rb') as fh:
reader= csv.reader(fh,'multiplex_info')
for row in reader:
print row


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


Re: [Tutor] ignoring certain lines while reading through CSV

2012-01-27 Thread Joel Goldstick
On Fri, Jan 27, 2012 at 5:13 PM, Abhishek Pratap  wrote:
> Hi Guys
>
> I am wondering if there is a keyword to ignore certain lines ( for eg
> lines starting with # ) when I am reading them through stl module csv.
>
> Example code:
>
> input_file = sys.argv[1]
> csv.register_dialect('multiplex_info',delimiter=' ')
>
> with open(input_file, 'rb') as fh:
>    reader= csv.reader(fh,'multiplex_info')
>    for row in reader:
>        print row
>
>
> best,
> -Abhi
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

You could look up the docs for csv.reader, but if there isn't, in your
for loop you can use row[0].startswith('"#")  to check if your line
starts with #.
Can you show what the row looks like?

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


Re: [Tutor] ignoring certain lines while reading through CSV

2012-01-27 Thread Abhishek Pratap
Hi Joel

Here is a sample

['1', 'AAA', '4344', '0.001505'] : want to keep this one

['#', 'AAA', '4344', '0.001505'] : and throw this one


You are right I am checking after parsing. I dint find an option in
csv.reader to ignore lines.

-Abhi





On Fri, Jan 27, 2012 at 2:42 PM, Joel Goldstick
 wrote:
> On Fri, Jan 27, 2012 at 5:13 PM, Abhishek Pratap  
> wrote:
>> Hi Guys
>>
>> I am wondering if there is a keyword to ignore certain lines ( for eg
>> lines starting with # ) when I am reading them through stl module csv.
>>
>> Example code:
>>
>> input_file = sys.argv[1]
>> csv.register_dialect('multiplex_info',delimiter=' ')
>>
>> with open(input_file, 'rb') as fh:
>>    reader= csv.reader(fh,'multiplex_info')
>>    for row in reader:
>>        print row
>>
>>
>> best,
>> -Abhi
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> You could look up the docs for csv.reader, but if there isn't, in your
> for loop you can use row[0].startswith('"#")  to check if your line
> starts with #.
> Can you show what the row looks like?
>
> --
> Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ignoring certain lines while reading through CSV

2012-01-27 Thread Joel Goldstick
On Fri, Jan 27, 2012 at 5:48 PM, Abhishek Pratap  wrote:
> Hi Joel
>
> Here is a sample
>
> ['1', 'AAA', '4344', '0.001505'] : want to keep this one
>
> ['#', 'AAA', '4344', '0.001505'] : and throw this one

Ok, so you are getting single quotes around your data.  So do
row[0].startswith("#") to test your row.
You may be able to test for row[0]=="#" if you always get only the #
in the first position of the row.
>
>
> You are right I am checking after parsing. I dint find an option in
> csv.reader to ignore lines.
>
> -Abhi
>
>
>
>
>
> On Fri, Jan 27, 2012 at 2:42 PM, Joel Goldstick
>  wrote:
>> On Fri, Jan 27, 2012 at 5:13 PM, Abhishek Pratap  
>> wrote:
>>> Hi Guys
>>>
>>> I am wondering if there is a keyword to ignore certain lines ( for eg
>>> lines starting with # ) when I am reading them through stl module csv.
>>>
>>> Example code:
>>>
>>> input_file = sys.argv[1]
>>> csv.register_dialect('multiplex_info',delimiter=' ')
>>>
>>> with open(input_file, 'rb') as fh:
>>>    reader= csv.reader(fh,'multiplex_info')
>>>    for row in reader:
>>>        print row
>>>
>>>
>>> best,
>>> -Abhi
>>> ___
>>> Tutor maillist  -  Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>> You could look up the docs for csv.reader, but if there isn't, in your
>> for loop you can use row[0].startswith('"#")  to check if your line
>> starts with #.
>> Can you show what the row looks like?
>>
-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ignoring certain lines while reading through CSV

2012-01-27 Thread Abhishek Pratap
Thansk Joel. Thats exactly what I am doing.

-A

On Fri, Jan 27, 2012 at 3:04 PM, Joel Goldstick
 wrote:
> On Fri, Jan 27, 2012 at 5:48 PM, Abhishek Pratap  
> wrote:
>> Hi Joel
>>
>> Here is a sample
>>
>> ['1', 'AAA', '4344', '0.001505'] : want to keep this one
>>
>> ['#', 'AAA', '4344', '0.001505'] : and throw this one
>
> Ok, so you are getting single quotes around your data.  So do
> row[0].startswith("#") to test your row.
> You may be able to test for row[0]=="#" if you always get only the #
> in the first position of the row.
>>
>>
>> You are right I am checking after parsing. I dint find an option in
>> csv.reader to ignore lines.
>>
>> -Abhi
>>
>>
>>
>>
>>
>> On Fri, Jan 27, 2012 at 2:42 PM, Joel Goldstick
>>  wrote:
>>> On Fri, Jan 27, 2012 at 5:13 PM, Abhishek Pratap  
>>> wrote:
 Hi Guys

 I am wondering if there is a keyword to ignore certain lines ( for eg
 lines starting with # ) when I am reading them through stl module csv.

 Example code:

 input_file = sys.argv[1]
 csv.register_dialect('multiplex_info',delimiter=' ')

 with open(input_file, 'rb') as fh:
    reader= csv.reader(fh,'multiplex_info')
    for row in reader:
        print row


 best,
 -Abhi
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor
>>>
>>> You could look up the docs for csv.reader, but if there isn't, in your
>>> for loop you can use row[0].startswith('"#")  to check if your line
>>> starts with #.
>>> Can you show what the row looks like?
>>>
> --
> Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] compile time calculator

2012-01-27 Thread Marc Tompkins
On Fri, Jan 27, 2012 at 7:46 AM, Surya K  wrote:

>  Hi,
>
> I want to calculate compile time for my puzzles.
>

Since nobody else has mentioned it yet...
http://xkcd.com/303/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Rounding Error

2012-01-27 Thread Michael Lewis
I am trying to round a float to two decimals, but I am getting the
following error:

Traceback (most recent call last):
  File "", line 1, in 
PaintingProject()
  File "C:/Python27/Homework/Labs/Lab 03_5.py", line 42, in PaintingProject
print 'That will cost you $%f.' %(round(5.6523),2)
TypeError: not all arguments converted during string formatting

Basically, I am writing a program to ask a user how many square feet they
need to paint. I then calculate how many cans of paint they need and will
also show the total purchase price. I've tried this two ways, and the first
way I am semi-successful meaning that my output is rounding but it displays
a number of zero's after the number rounds. The second way, I am getting
the error mentioned above. What am I doing wrong? How can I do this better?
(note, for the sake of brevity, I only show the code in question and not
the whole program).

total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX)
total = round(total,2)
print 'For %d square feet, you\'ll need %d cans of paint.'
%(square_feet, cans)
print 'That will cost you $%f.' %(total)



total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX)
print 'For %d square feet, you\'ll need %d cans of paint.'
%(square_feet, cans)
print 'That will cost you $%f.' %(round(total),2)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding Error

2012-01-27 Thread Michael Lewis
Update

I am trying to round a float to two decimals.
>
> Basically, I am writing a program to ask a user how many square feet they
> need to paint. I then calculate how many cans of paint they need and will
> also show the total purchase price. I've tried this two ways, and both ways
> I am semi-successful meaning that my output is rounding but it displays a
> number of zero's after the number rounds. How can I make the zero's stop
> displaying?
>



> total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX)
> total = round(total,2)
> print 'For %d square feet, you\'ll need %d cans of paint.'
> %(square_feet, cans)
> print 'That will cost you $%f.' %(total)
>
>
>
> total = PRICE_PER_CAN * cans + (PRICE_PER_CAN * cans * TAX)
> print 'For %d square feet, you\'ll need %d cans of paint.'
> %(square_feet, cans)
> print 'That will cost you $%f.' %round(total,2)
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding Error

2012-01-27 Thread Steven D'Aprano

Michael Lewis wrote:

I am trying to round a float to two decimals, but I am getting the
following error:

Traceback (most recent call last):
  File "", line 1, in 
PaintingProject()
  File "C:/Python27/Homework/Labs/Lab 03_5.py", line 42, in PaintingProject
print 'That will cost you $%f.' %(round(5.6523),2)
TypeError: not all arguments converted during string formatting




Basically, I am writing a program to ask a user how many square feet they
need to paint.


All this is irrelevant to your problem. Read the error message: it says that 
you have more arguments than expected when doing the string formatting. 
round() doesn't enter into it. You can get the same error if you do this:


print 'That will cost you $%f.' % (5.6523, 2)

You have one % target in the string, but two numbers trying to fit into it, 
and Python refuses to guess if you want to use 5.6523 or 2.


And that should give you the clue you need to solve the problem, which brings 
it back to round(). You want to round to two decimal places, but you don't put 
the 2 inside the call to round. You have:


(round(5.6523), 2)

which gives you two numbers: (6.0, 2)

but what you actually want is:

round(5.6523, 2)

which gives you the number you want, 5.65.

And finally, we come all the way back to the beginning again and say That's 
not the right way to do it! Don't round the number *outside* of the string 
formatting, get the string formatting to do it for you:


print 'That will cost you $%.2f.' % 5.6523

will give you the result you want.




--
Steven

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


Re: [Tutor] Rounding Error

2012-01-27 Thread Devin Jeanpierre
On Sat, Jan 28, 2012 at 1:20 AM, Steven D'Aprano  wrote:
> And finally, we come all the way back to the beginning again and say That's
> not the right way to do it! Don't round the number *outside* of the string
> formatting, get the string formatting to do it for you:

Reason being because repr(round(0.1, 2)) != '0.1' (on older Pythons).
String formatting does the right thing.

Also don't use floats for currency, they can attract rounding errors
and can't represent many common amounts with 100% precision, the way a
Decimal or Fraction can (see decimal, fractions modules). For example,
it can't represent 0.1 exactly, thus leading to the above situation.

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