Re: os.path.realpath(path) bug on win7 ?

2013-01-05 Thread Chris Rebert
On Sat, Jan 5, 2013 at 10:55 PM, iMath <2281570...@qq.com> wrote:
>
> os.path.realpath(path)  bug on win7 ?
>
> Temp.link is a Symbolic link
> Its target location is C:\test\test1
> But
> >>> os.path.realpath(r'C:\Users\SAMSUNG\Temp.link\test2')
> 'C:\\Users\\SAMSUNG\\Temp.link\\test2'
>
> I thought the return value should be ' C:\\test\\test1\\test2'
>
> Is it a bug ? anyone can clear it to me ?

What does os.path.islink('C:/Users/SAMSUNG/Temp.link') report?

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


os.path.realpath(path) bug on win7 ?

2013-01-05 Thread iMath

os.path.realpath(path)  bug on win7 ?Temp.link is a Symbolic linkIts target location is C:\test\test1But >>> os.path.realpath(r'C:\Users\SAMSUNG\Temp.link\test2')'C:\\Users\\SAMSUNG\\Temp.link\\test2'I thought the return value should be ' C:\\test\\test1\\test2'Is it a bug ? anyone can clear it to me ?-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Mitya Sirenef

On 01/05/2013 03:35 AM, Sia wrote:

I have strings such as:

>
> tA.-2AG.-2AG,-2ag
> or
> .+3ACG.+5CAACG.+3ACG.+3ACG
>
> The plus and minus signs are always followed by a number (say, i). I 
want python to find each single plus or minus, remove the sign, the 
number after it and remove i characters after that. So the two strings 
above become:

>
> tA..,
> and
> ...
>
> How can I do that?
> Thanks.


I think it's a bit cleaner and nicer to do something similar to
itertools.takewhile but takewhile 'eats' a single next value.
I was actually doing some stuff that also needed this. I wonder if
there's a more elegant, robust way to do this?

Here's what I got for now:


class BIterator(object):
"""Iterator with 'buffered' takewhile."""

def __init__(self, seq):
self.seq= iter(seq)
self.buffer = []
self.end_marker = object()
self.last   = None

def consume(self, n):
for _ in range(n): self.next()

def next(self):
val = self.buffer.pop() if self.buffer else next(self.seq, 
self.end_marker)

self.last = val
return val

def takewhile(self, test):
lst = []
while True:
val = self.next()
if val is self.end_marker:
return lst
elif test(val):
lst.append(val)
else:
self.buffer.append(val)
return lst

def joined_takewhile(self, test):
return ''.join(self.takewhile(test))

def done(self):
return bool(self.last is self.end_marker)


s = ".+3ACG.+5CAACG.+3ACG.+3ACG"
not_plusminus = lambda x: x not in "+-"
isdigit   = lambda x: x.isdigit()

def process(s):
lst = []
s   = BIterator(s)

while True:
lst.extend(s.takewhile(not_plusminus))
if s.done(): break
s.next()
n = int(s.joined_takewhile(isdigit))
s.consume(n)

return ''.join(lst)


print(process(s))


Obviously it assumes the input is well-formed, but the logic would be
very easy to change to, for example, check for s.done() after each step.

 - mitya



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

--
http://mail.python.org/mailman/listinfo/python-list


SOLUTIONS MANUAL TO A Course in Modern Mathematical Physics by Peter Szekeres

2013-01-05 Thread reganrexman
I have solutions manuals to all problems and exercises in these textbooks. To 
get one in an electronic format contact me at: reganrexman(at)gmail(dot)com and 
let me know its title, author and edition. Please this service is NOT free.

SOLUTIONS MANUAL TO A First Course in Differential Equations  (7th ed.)  Zill & 
 Diferential Equations  (5th ed.)Zill & Cullen 
SOLUTIONS MANUAL TO 2500 Solved Problems in Fluid Mechanics & Hydraulics 
Schaums by Evett, cheng Liu
SOLUTIONS MANUAL TO A Course in Game Theory by Osborne, Rubinstein
SOLUTIONS MANUAL TO A Course in Modern Mathematical Physics by Peter Szekeres
SOLUTIONS MANUAL TO A Course in Ordinary Differential Equations by Swift, Wirkus
SOLUTIONS MANUAL TO A First Course in Abstract Algebra (7th Ed., John B. 
Fraleigh)  
SOLUTIONS MANUAL TO A First Course in Differential Equations -  The Classic 
Fifth Edition By Zill, Dennis G
SOLUTIONS MANUAL TO A First Course in Differential Equations, 9th Ed by Dennis 
G. Zill
SOLUTIONS MANUAL TO A First Course In Probability 7th Edition by Sheldon M. Ross
SOLUTIONS MANUAL TO A First Course in Probability Theory, 6th edition, by S. 
Ross.
SOLUTIONS MANUAL TO A First Course in String Theory, 2004, Barton Zwiebach
SOLUTIONS MANUAL TO A First Course in the Finite Element Method, 4th Edition  
logan
SOLUTIONS MANUAL TO A Practical Introduction to Data Structures and Algorithm 
Analysis 2Ed by Shaffer
SOLUTIONS MANUAL TO A Quantum Approach to Condensed Matter Physics (Philip L. 
Taylor & Olle Heinonen)
SOLUTIONS MANUAL TO A Short Course in General Relativity 2e by J. Foster and J. 
D. Nightingale
SOLUTIONS MANUAL TO A Short Introduction to Quantum Information and Quantum 
Computation by Michel Le Bellac
SOLUTIONS MANUAL TO A Transition to Advanced Mathematics 5th E by Smith, Eggen, 
Andre 
SOLUTIONS MANUAL TO Accounting Principles 8e by Kieso, Kimmel
SOLUTIONS MANUAL TO Accounting principles 8th Ed by Weygandt
SOLUTIONS MANUAL TO Accounting, 23 Ed by Carl S. Warren, James M. Reeve, 
Jonathan Duchac
SOLUTIONS MANUAL TO Accounting,8th Ed by Horngren,Harrison, Oliver
SOLUTIONS MANUAL TO Adaptive Control, 2nd. Ed., by Astrom, Wittenmark
SOLUTIONS MANUAL TO Adaptive Filter Theory (4th Ed., Simon Haykin)
SOLUTIONS MANUAL TO Advanced Accounting 10E international ED by Beams , 
Clement, Anthony, Lowensohn
SOLUTIONS MANUAL TO Advanced accounting 9th Ed by Hoyle, Schaefer
SOLUTIONS MANUAL TO Advanced Calculus Gerald B. Folland
SOLUTIONS MANUAL TO Advanced Digital Design with the Verilog HDL by Michael D. 
Ciletti
SOLUTIONS MANUAL TO Advanced Dynamics (Greenwood)
SOLUTIONS MANUAL TO Advanced Engineering Electromagnetics by Constantine A. 
Balanis
SOLUTIONS MANUAL TO Advanced Engineering Mathematics 3rd ed zill
SOLUTIONS MANUAL TO Advanced Engineering Mathematics 8Ed Erwin Kreyszig
SOLUTIONS MANUAL TO Advanced Engineering Mathematics by Erwin Kreyszig, 9th ed
SOLUTIONS MANUAL TO Advanced Engineering Mathematics, 6th Edition by Peter V. 
O'Neil
SOLUTIONS MANUAL TO Advanced Engineering Mathematics,2E, by Zill, Cullen
SOLUTIONS MANUAL TO Advanced Engineering Thermodynamics, 3rd Edition by Adrian 
Bejan
SOLUTIONS MANUAL TO Advanced Financial Accounting  by Baker
SOLUTIONS MANUAL TO Advanced Financial Accounting 5 Ed by Baker 
SOLUTIONS MANUAL TO Advanced Industrial Economics by Martin
SOLUTIONS MANUAL TO Advanced Industrial Economics, 2nd ED Stephen Martin
SOLUTIONS MANUAL TO Advanced Macroeconomics 2nd edition  by David Romer
SOLUTIONS MANUAL TO Advanced Macroeconomics, by David Romer
SOLUTIONS MANUAL TO Advanced Mechanics of Materials 6th ed by Boresi, Schmidt
SOLUTIONS MANUAL TO Advanced Modern Engineering Mathematics 3rd Ed Glyn James
SOLUTIONS MANUAL TO Advanced Modern Engineering Mathematics 4th Ed Glyn James
SOLUTIONS MANUAL TO Advanced Modern Engineering Mathematics, 3rd Ed., by G. 
James
SOLUTIONS MANUAL TO Advanced Organic Chemistry Part A- Structure and Mechanisms 
5th E by Carey, Sundberg
SOLUTIONS MANUAL TO Aircraft Structures for Engineering Students (4th Ed., 
T.H.G. Megson)
SOLUTIONS MANUAL TO Algebra & Trigonometry and Precalculus, 3rd Ed By Beecher, 
Penna, Bittinger
SOLUTIONS MANUAL TO Algebra Baldor
SOLUTIONS MANUAL TO Algebra-By Thomas W. Hungerford
SOLUTIONS MANUAL TO Algorithm Design (Jon Kleinberg & ?‰va Tardos) 
SOLUTIONS MANUAL TO An Interactive Introduction to Mathematical Analysis 2nd E 
(Jonathan Lewin)
SOLUTIONS MANUAL TO An Introduction To Analysis 4th Ed by William Wade
SOLUTIONS MANUAL TO An Introduction to Database Systems (8th Ed., C.J. Date)
SOLUTIONS MANUAL TO An Introduction to Economic Dynamics by Ronald Shone 
SOLUTIONS MANUAL TO An Introduction to Modern Astrophysics (2nd Ed., Bradley W. 
Carroll & Dale A. Ostlie)
SOLUTIONS MANUAL TO An Introduction to Numerical Analysis By Endre Süli,David 
F. Mayers
SOLUTIONS MANUAL TO An Introduction to Ordinary Differential Equations (James 
C. Robinson)
SOLUTIONS MANUAL TO An Introduction to Signals and Systems by John Stuller
SOLUTIONS MANUAL TO An Introducti

SOLUTIONS MANUAL TO A Course in Modern Mathematical Physics by Peter Szekeres

2013-01-05 Thread reganrexman
I have solutions manuals to all problems and exercises in these textbooks. To 
get one in an electronic format contact me at: reganrexman(at)gmail(dot)com and 
let me know its title, author and edition. Please this service is NOT free.

SOLUTIONS MANUAL TO A First Course in Differential Equations  (7th ed.)  Zill & 
 Diferential Equations  (5th ed.)Zill & Cullen 
SOLUTIONS MANUAL TO 2500 Solved Problems in Fluid Mechanics & Hydraulics 
Schaums by Evett, cheng Liu
SOLUTIONS MANUAL TO A Course in Game Theory by Osborne, Rubinstein
SOLUTIONS MANUAL TO A Course in Modern Mathematical Physics by Peter Szekeres
SOLUTIONS MANUAL TO A Course in Ordinary Differential Equations by Swift, Wirkus
SOLUTIONS MANUAL TO A First Course in Abstract Algebra (7th Ed., John B. 
Fraleigh)  
SOLUTIONS MANUAL TO A First Course in Differential Equations -  The Classic 
Fifth Edition By Zill, Dennis G
SOLUTIONS MANUAL TO A First Course in Differential Equations, 9th Ed by Dennis 
G. Zill
SOLUTIONS MANUAL TO A First Course In Probability 7th Edition by Sheldon M. Ross
SOLUTIONS MANUAL TO A First Course in Probability Theory, 6th edition, by S. 
Ross.
SOLUTIONS MANUAL TO A First Course in String Theory, 2004, Barton Zwiebach
SOLUTIONS MANUAL TO A First Course in the Finite Element Method, 4th Edition  
logan
SOLUTIONS MANUAL TO A Practical Introduction to Data Structures and Algorithm 
Analysis 2Ed by Shaffer
SOLUTIONS MANUAL TO A Quantum Approach to Condensed Matter Physics (Philip L. 
Taylor & Olle Heinonen)
SOLUTIONS MANUAL TO A Short Course in General Relativity 2e by J. Foster and J. 
D. Nightingale
SOLUTIONS MANUAL TO A Short Introduction to Quantum Information and Quantum 
Computation by Michel Le Bellac
SOLUTIONS MANUAL TO A Transition to Advanced Mathematics 5th E by Smith, Eggen, 
Andre 
SOLUTIONS MANUAL TO Accounting Principles 8e by Kieso, Kimmel
SOLUTIONS MANUAL TO Accounting principles 8th Ed by Weygandt
SOLUTIONS MANUAL TO Accounting, 23 Ed by Carl S. Warren, James M. Reeve, 
Jonathan Duchac
SOLUTIONS MANUAL TO Accounting,8th Ed by Horngren,Harrison, Oliver
SOLUTIONS MANUAL TO Adaptive Control, 2nd. Ed., by Astrom, Wittenmark
SOLUTIONS MANUAL TO Adaptive Filter Theory (4th Ed., Simon Haykin)
SOLUTIONS MANUAL TO Advanced Accounting 10E international ED by Beams , 
Clement, Anthony, Lowensohn
SOLUTIONS MANUAL TO Advanced accounting 9th Ed by Hoyle, Schaefer
SOLUTIONS MANUAL TO Advanced Calculus Gerald B. Folland
SOLUTIONS MANUAL TO Advanced Digital Design with the Verilog HDL by Michael D. 
Ciletti
SOLUTIONS MANUAL TO Advanced Dynamics (Greenwood)
SOLUTIONS MANUAL TO Advanced Engineering Electromagnetics by Constantine A. 
Balanis
SOLUTIONS MANUAL TO Advanced Engineering Mathematics 3rd ed zill
SOLUTIONS MANUAL TO Advanced Engineering Mathematics 8Ed Erwin Kreyszig
SOLUTIONS MANUAL TO Advanced Engineering Mathematics by Erwin Kreyszig, 9th ed
SOLUTIONS MANUAL TO Advanced Engineering Mathematics, 6th Edition by Peter V. 
O'Neil
SOLUTIONS MANUAL TO Advanced Engineering Mathematics,2E, by Zill, Cullen
SOLUTIONS MANUAL TO Advanced Engineering Thermodynamics, 3rd Edition by Adrian 
Bejan
SOLUTIONS MANUAL TO Advanced Financial Accounting  by Baker
SOLUTIONS MANUAL TO Advanced Financial Accounting 5 Ed by Baker 
SOLUTIONS MANUAL TO Advanced Industrial Economics by Martin
SOLUTIONS MANUAL TO Advanced Industrial Economics, 2nd ED Stephen Martin
SOLUTIONS MANUAL TO Advanced Macroeconomics 2nd edition  by David Romer
SOLUTIONS MANUAL TO Advanced Macroeconomics, by David Romer
SOLUTIONS MANUAL TO Advanced Mechanics of Materials 6th ed by Boresi, Schmidt
SOLUTIONS MANUAL TO Advanced Modern Engineering Mathematics 3rd Ed Glyn James
SOLUTIONS MANUAL TO Advanced Modern Engineering Mathematics 4th Ed Glyn James
SOLUTIONS MANUAL TO Advanced Modern Engineering Mathematics, 3rd Ed., by G. 
James
SOLUTIONS MANUAL TO Advanced Organic Chemistry Part A- Structure and Mechanisms 
5th E by Carey, Sundberg
SOLUTIONS MANUAL TO Aircraft Structures for Engineering Students (4th Ed., 
T.H.G. Megson)
SOLUTIONS MANUAL TO Algebra & Trigonometry and Precalculus, 3rd Ed By Beecher, 
Penna, Bittinger
SOLUTIONS MANUAL TO Algebra Baldor
SOLUTIONS MANUAL TO Algebra-By Thomas W. Hungerford
SOLUTIONS MANUAL TO Algorithm Design (Jon Kleinberg & ?‰va Tardos) 
SOLUTIONS MANUAL TO An Interactive Introduction to Mathematical Analysis 2nd E 
(Jonathan Lewin)
SOLUTIONS MANUAL TO An Introduction To Analysis 4th Ed by William Wade
SOLUTIONS MANUAL TO An Introduction to Database Systems (8th Ed., C.J. Date)
SOLUTIONS MANUAL TO An Introduction to Economic Dynamics by Ronald Shone 
SOLUTIONS MANUAL TO An Introduction to Modern Astrophysics (2nd Ed., Bradley W. 
Carroll & Dale A. Ostlie)
SOLUTIONS MANUAL TO An Introduction to Numerical Analysis By Endre Süli,David 
F. Mayers
SOLUTIONS MANUAL TO An Introduction to Ordinary Differential Equations (James 
C. Robinson)
SOLUTIONS MANUAL TO An Introduction to Signals and Systems by John Stuller
SOLUTIONS MANUAL TO An Introducti

Good Python IDE

2013-01-05 Thread Sourabh Mhaisekar
Hello All, 
I am recently started couple of projects in Python, one in Python GTK and one 
in Python Qt. I want a good IDE (For Windows ) for Python which gives support 
for Python as well as PyGtk and PyQt. 

Features I am looking for 
* Support for Core Python Auto-completion.
* Support for PyGtk and PyQt
* Support for either Bazaar (preferred) or CVS

Thanks ! 

- Sourabh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python programming philosophy

2013-01-05 Thread Sourabh Mhaisekar
The main philosophy behind python (according to me) is rapid application 
development. The python gives you convinent and powerful tool to develop 
sophisticated application rapidly. 

You can find more details on 
http://www.python.org/about/success/
http://www.python.org/about/success/#rapid-application-development

Have a great python time. 

- Sourabh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python programming philosophy

2013-01-05 Thread 88888 Dihedral
chaouche yacine於 2013年1月6日星期日UTC+8上午6時34分38秒寫道:
> The compiler reads your source code and parses it into parse trees. This is 
> first step. It then takes the parse trees and transform them into abstract 
> syntax trees, which are like a DOM tree in an HTML file, and then transform 
> that AST into a control flow graph, and finally a bytecode is produced out of 
> that control flow graph. The pyc files you see are this bytecode, so they are 
> produced at the end. Anytime you edit your .py file, a new .pyc file is 
> created if you invoke the python interpreter myfile.py on the former. If your 
> .py file doesn't change, the .pyc file stays the same.
> 
> Just like with java, this allows you to write a single .py file that can work 
> on any platform without changing the source file, because all the cross 
> platform issues are handled by the virtual machine.
> 
> 
> 
> 
> 
>  From: Nac Temha 
> To: pytho...@python.org 
> Sent: Saturday, January 5, 2013 11:05 PM
> Subject: Python programming philosophy
> 
> 
> Hello,
> 
> 
> 
> I want to learn working principle of python as broadly. How to interpret the 
> python?  For example, what is pyc files and when does it occur?
> Can you explain them? Thanks in advance.
> -- 
> http://mail.python.org/mailman/listinfo/python-list

Yes, check JYTHON tutorials to understand dynamic types.

Java is still a fixed type computer language.
-- 
http://mail.python.org/mailman/listinfo/python-list


A question about thrift performance.

2013-01-05 Thread Vincent
Hi, all

I have issue of thrift-performance in python, does anyone has an experience on 
thrift-in-python?

My question in stackoverflow:

http://stackoverflow.com/questions/14171227/why-is-thrift-binary-protocol-serialization-so-much-slow


Copy the question to here(open stackoverflow to check pretty-print question 
content):

I'm newbie on thrift. I wrote a thrift server in python, also client in python 
too.

Here is my thrift defination:
struct RatingByReport {
1: required string ticker,
2: required i32 cnt_institution,
3: optional list strong_buy,
4: optional list buy,
5: optional list neutral,
6: optional list sell,
7: optional list strong_sell,
8: optional i32 cnt_maintain,
9: optional i32 cnt_upgrade,
10: optional i32 cnt_downgrade,
11: optional i32 avg_score,
12: optional string adjustment
}

struct TableRatingByReport {
1: required list head,
2: required list body,
3: optional struct.CadaTranslation translation
}



service china{
void ping(),
TableRatingByReport rating_byreport(1:string ticker) throws 
(1:struct.CadaInternalError error)
}
Here is my server side:
handler = StockChinaHandler()
processor = china.Processor(handler)
#startup()

transport = TSocket.TServerSocket(port=30303)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
#server = TProcessPoolServer.TProcessPoolServer(processor, transport,
#tfactory, pfactory)

print "Start server..."
import cProfile
print >>open('/tmp/test.log', 'w'), cProfile.run('server.serve()',
sort='cumulative')
#server.serve()
print "done!"
Client side:
# Make socket
transport = TSocket.TSocket('localhost', 30303)

# Buffering is critical. Raw sockets are very slow
transport = TTransport.TBufferedTransport(transport)

# Wrap in a protocol
protocol = TBinaryProtocol.TBinaryProtocol(transport)

# Create a client to use the protocol encoder
client = china.Client(protocol)

# Connect!
transport.open()

client.ping()
print "ping()"

print msg
msg = client.rating_byreport('2012-01-04')
print msg
transport.close()
cProfile result:
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
10.0000.000  230.968  230.968 :1()
10.0000.000  230.968  230.968 TServer.py:74(serve)
30.0000.000  225.967   75.322 TSocket.py:172(accept)
30.0000.000  225.967   75.322 socket.py:194(accept)
3  225.967   75.322  225.967   75.322 {method 'accept' of 
'_socket.socket' objects}
50.0030.0014.9930.999 china.py:140(process)
10.0000.0003.2003.200 
china.py:177(process_rating_byreport)
10.0000.0002.3662.366 china.py:500(write)
10.0030.0032.3662.366 ttypes.py:515(write)
 14550.2610.0002.3630.002 ttypes.py:364(write)
   160.2460.0001.9950.000 TCompactProtocol.py:38(nested)
   1458800.2980.0001.6400.000 
TCompactProtocol.py:255(__writeString)
   181.3700.0761.3700.076 {method 'recv' of 
'_socket.socket' objects}
50.0000.0001.2920.258 
TCompactProtocol.py:306(readMessageBegin)
   130.0000.0001.2920.099 
TCompactProtocol.py:286(__readUByte)
   260.0000.0001.2910.050 TTransport.py:54(readAll)
   260.0000.0001.2910.050 TTransport.py:154(read)
50.0000.0001.2910.258 TSocket.py:101(read)
In my case, TableRatingByReport instance got a body with 1400 rows(list\), and 
It cost over 3 seconds(function *process_rating_byreport*, which is auto 
generate by thift) to generate binnary content. I don't know why it is so slow.

Using json to serialize the same data, It's only spend less than 200 ms.

I'm wondering did I use the uncorrect way to manipulate thrift?

Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python programming philosophy

2013-01-05 Thread chaouche yacine
The compiler reads your source code and parses it into parse trees. This is 
first step. It then takes the parse trees and transform them into abstract 
syntax trees, which are like a DOM tree in an HTML file, and then transform 
that AST into a control flow graph, and finally a bytecode is produced out of 
that control flow graph. The pyc files you see are this bytecode, so they are 
produced at the end. Anytime you edit your .py file, a new .pyc file is created 
if you invoke the python interpreter myfile.py on the former. If your .py file 
doesn't change, the .pyc file stays the same.
Just like with java, this allows you to write a single .py file that can work 
on any platform without changing the source file, because all the cross 
platform issues are handled by the virtual machine.




From: Nac Temha 
To: python-list@python.org 
Sent: Saturday, January 5, 2013 11:05 PM
Subject: Python programming philosophy


Hello,



I want to learn working principle of python as broadly. How to interpret the 
python?  For example, what is pyc files and when does it occur?
Can you explain them? Thanks in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import of ttk

2013-01-05 Thread Terry Reedy

On 1/5/2013 2:21 PM, Verde Denim wrote:

On 01/04/2013 11:39 PM, Terry Reedy wrote:

On 1/4/2013 11:02 PM, Verde Denim wrote:

In reading through one of the learning articles, I have a bit of code
that imports ttk, but I apparently don't have this installed. I've
looked up the svn checkout for python-tk, and have checked it out
(read-only), but still get the same error. I'm running 2.6.6 python, if
that helps.


Upgrade to the latest 2.7 or even 3.3 if at all possible.


Show the line of code that did not work and the traceback. What system
are you running on and what tcl/tk installation does it have? ttk is
included with any 8.5 installation. tile is often included with 8.4
installations and should be picked up as well.

  The article I'm looking at is here -

http://www.zetcode.com/gui/tkinter/introduction/




The line is -
16 from ttk import Frame, Button, Style

$ python tkinter_tut1.py
Traceback (most recent call last):
   File "tkinter_tut1.py", line 16, in 
 from ttk import Frame, Button, Style
ImportError: No module named ttk

I'm running on Debian Squeeze, and do show both 8.4 and 8.5 of tcl


On my Windows 2.7 installation, directory /Lib contains directory 
/lib-tk (which is added to the path). /lib-tk contains files Tkinter.py 
and ttk.py, among others. If you have ttk.py, then I do not think you 
should get that specific message; if there were a problem finding 
tcl/tk, it should say something else. If you do not have that file, as 
it seems, then your installation is incomplete. So check your 
/Lib/lib-tk. If you do not know where it is


import sys
print(sys.path)

Portability note: In 3.x, /lib-tk was renamed /tkinter and removed from 
the path. Tkinter.py was renamed __init__.py to make the renamed 
/tkinter an importable package. So 'import Tkinter becomes 'import 
tkinter', while 'import ttk', etcetera, is now 'import tkinter.ttk', 
etcetera. 2to3 should make the fixes.


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python programming philosophy

2013-01-05 Thread Chris Angelico
On Sun, Jan 6, 2013 at 9:05 AM, Nac Temha  wrote:
> Hello,
>
> I want to learn working principle of python as broadly. How to interpret the
> python?  For example, what is pyc files and when does it occur?
> Can you explain them? Thanks in advance.

The pyc files aren't really a philosophical point, they're just a
cache of the compiled versions of .py files - the assumption being
that if you import it as a module once, chances are you'll import it
again later, and libraries tend not to change much.

For the philosophy of Python, type this at the interactive prompt:

import this

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reduce expression to test sublist

2013-01-05 Thread Dave Angel
On 01/05/2013 04:55 PM, Terry Reedy wrote:
> On 1/5/2013 1:58 PM, Dave Angel wrote:
>
>> If you're trying to make a faster loop, then I suggest you look into set
>> differences.  Turn both lists into sets, and subtract them.   Something
>> like (untested):
>>
>> result =  not bool( set(lst1) - set(lst2) )
>
> This does not return False as soon as an item in set1 is found that is
> not in set2.
>
> set(lst1) < set(lst2)
>
> will, and directly return False/True. The OP is trying to compute the
> lst1 < lst2, where lst1 and lst2 are interpreted as sets, rather than
> as sequences with the lexicographic ordering default.
>

Thanks.  I wasn't aware that sets supported ordered comparison that way,
though it makes perfect sense now that you point it out.


-- 

DaveA

-- 
http://mail.python.org/mailman/listinfo/python-list


Python programming philosophy

2013-01-05 Thread Nac Temha
Hello,

I want to learn working principle of python as broadly. How to interpret
the python?  For example, what is pyc files and when does it occur?
Can you explain them? Thanks in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python wiki gone?

2013-01-05 Thread Terry Reedy

On 1/5/2013 2:59 PM, Andrew Berg wrote:

On 2013.01.05 13:07, Lee Harr wrote:

When I go to wiki.python.org I get redirected to
http://wiki.python.org/moin/
which is 404 Not Found.

There's a security issue with moinmoin. The Python wiki is not the only
wiki offline for this reason.


For anyone doing such a thing in the future:
A replacement page "The Python wiki is off-line for maintenance." would 
have been nice.


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: reduce expression to test sublist

2013-01-05 Thread Terry Reedy

On 1/5/2013 1:25 PM, Asim wrote:

Hi All

The following reduce expression checks if every element of list lst1
is present in list lst2.  It works as expected for integer lists but
for lists of strings, it always returns False.

reduce( lambda x,y: (x in lst2) and (y in lst2), lst1)


reduce(lambda x, y: x and (y in lst2), lst1, True)

would work, but as other have said, you want to stops at the first 
False, which all() does, and if lst2 is a list of hashable items, x in 
set for O(1) rather than O(n) check.




Moreover, for the lists of strings the following for-loop gives
correct results when the above reduce expression doesn't.


You should include data for testing.



isSublist = True

> for i in lst1:
>   isSublist = isSublist and (i in> lst2)

If isSublist remains True, there is no need to rebind it

>   if not isSublist:
> isSublist = False

Setting isSublist False when it is False is redundant.


break


Taking into account the comments:

def is_sublist(a, b):
  b = set(b)  # optional, depending on contents
  for item in a:
if item not in b:
  return False
  else:  # not needed because return above
return True

The code for all() is similar, except that all takes an iterable, so 
that the testing is done as part of the input iterable.


def all(iterable):
  it = iter(iterable):
  for item in it:
if not it:
  return False:
  else:
return True

def issublist(a, b):
  b = set(b)
  return all(item in b for item in a)

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: reduce expression to test sublist

2013-01-05 Thread Terry Reedy

On 1/5/2013 1:58 PM, Dave Angel wrote:


If you're trying to make a faster loop, then I suggest you look into set
differences.  Turn both lists into sets, and subtract them.   Something
like (untested):

result =  not bool( set(lst1) - set(lst2) )


This does not return False as soon as an item in set1 is found that is 
not in set2.


set(lst1) < set(lst2)

will, and directly return False/True. The OP is trying to compute the 
lst1 < lst2, where lst1 and lst2 are interpreted as sets, rather than as 
sequences with the lexicographic ordering default.


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Roy Smith
In article ,
 Chris Angelico  wrote:

> On Sun, Jan 6, 2013 at 7:04 AM, Ian Kelly  wrote:
> > On Sat, Jan 5, 2013 at 8:57 AM, Chris Angelico  wrote:
> >> You miss my point, though. I went for simple Pythonic code, and never
> >> measured its performance, on the expectation that it's "good enough".
> >> Written in C, the state machine is probably WAY faster than splitting
> >> and then iterating. My C++ MUD client uses code similar to that to
> >> parse TELNET and ANSI codes from a stream of bytes in a socket (and
> >> one of its "states" is that there's no more data available, so wait on
> >> the socket); the rewrite in a high level language divides the string
> >> on "\xFF" for TELNET and "\x1B" for ANSI, working them separately, and
> >> then afterward splits on "\n" to divide into lines. The code's much
> >> less convoluted, it's easier to test different parts (because I can
> >> simply call the ANSI parser with a block of text), and on a modern
> >> computer, you can't see the performance difference (since you spend
> >> most of your time waiting for socket data anyway).
> >
> > Anecdotally and somewhat off-topic, when I wrote my own MUD client in
> > Python, I implemented both TELNET and ANSI parsing in Python using a
> > state machine processing one byte at a time (actually two state
> > machines - one at the protocol layer and one at the client layer; the
> > telnet module is a modified version of the twisted.conch.telnet
> > module).  I was worried that the processing would be too slow in
> > Python.  When I got it running, it turned out that there was a
> > noticeable lag between input being received and displayed.  But when I
> > profiled the issue it actually turned out that the rich text control I
> > was using, which was written in C++, wasn't able to handle a large
> > buffer gracefully.  The parsing code in Python did just fine and
> > didn't contribute to the lag issue at all.
> 
> The opposite decision, the same result. Performance was *good enough*.
> With Gypsum, my early performance problems were almost completely
> solved by properly handling the expose-event and only painting the
> parts that changed (I don't use a rich text control, I use a
> GTK2.DrawingArea). Text processing of something that's come over a
> network is seldom a problem; if it were, we'd see noticeably slower
> downloads over HTTPS than HTTP, and that just doesn't happen. I think
> (though I can't prove) that crypto written in C is probably more
> expensive than ANSI parsing written in Python.
> 
> ChrisA

It's rare to find applications these days that are truly CPU bound.  
Once you've used some reasonable algorithm, i.e. not done anything in 
O(n^2) that could have been done in O(n) or O(n log n), you will more 
often run up against I/O speed, database speed, network latency, memory 
exhaustion, or some such as the reason your code is too slow.

The upshot of this is that for most things, Python (even though it runs 
an order of magnitude slower than C), will always be *good enough*.

I'm sure I've mentioned this before, but the application code for 
Songza.com is 100% Python.  We pretty much can't even measure how much 
CPU time is spent running Python code.  Everything is database, network, 
and (occasionally) disk throughput.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reduce expression to test sublist

2013-01-05 Thread Jussi Piitulainen
Asim writes:

> Hi All
> 
> The following reduce expression checks if every element of list lst1
> is present in list lst2.  It works as expected for integer lists but
> for lists of strings, it always returns False.
> 
>reduce( lambda x,y: (x in lst2) and (y in lst2), lst1)

Possibly this:

  >>> True in [3, 1, 4]
  True
  >>> True in ["3", "1", "4"]
  False

Since reduce(f, [a, b, c]) == f(f(a,b),c), your x will be True or
False except in the innermost call where it is the first element of
the list being reduced.

It doesn't really work with integers either. Only in certain special
cases: very short lst1, or True in lst2.

> Moreover, for the lists of strings the following for-loop gives
> correct results when the above reduce expression doesn't.
> 
>isSublist = True
>for i in lst1:
>   isSublist = isSublist and (i in lst2)
>   if not isSublist:
>  isSublist = False
>  break
> 
> Can someone help me understand why?

Consider reduce(lambda x, y: x and (y in whatever), ys, True).

Maybe also consider all(y in whatever for y in ys).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Chris Angelico
On Sun, Jan 6, 2013 at 7:04 AM, Ian Kelly  wrote:
> On Sat, Jan 5, 2013 at 8:57 AM, Chris Angelico  wrote:
>> You miss my point, though. I went for simple Pythonic code, and never
>> measured its performance, on the expectation that it's "good enough".
>> Written in C, the state machine is probably WAY faster than splitting
>> and then iterating. My C++ MUD client uses code similar to that to
>> parse TELNET and ANSI codes from a stream of bytes in a socket (and
>> one of its "states" is that there's no more data available, so wait on
>> the socket); the rewrite in a high level language divides the string
>> on "\xFF" for TELNET and "\x1B" for ANSI, working them separately, and
>> then afterward splits on "\n" to divide into lines. The code's much
>> less convoluted, it's easier to test different parts (because I can
>> simply call the ANSI parser with a block of text), and on a modern
>> computer, you can't see the performance difference (since you spend
>> most of your time waiting for socket data anyway).
>
> Anecdotally and somewhat off-topic, when I wrote my own MUD client in
> Python, I implemented both TELNET and ANSI parsing in Python using a
> state machine processing one byte at a time (actually two state
> machines - one at the protocol layer and one at the client layer; the
> telnet module is a modified version of the twisted.conch.telnet
> module).  I was worried that the processing would be too slow in
> Python.  When I got it running, it turned out that there was a
> noticeable lag between input being received and displayed.  But when I
> profiled the issue it actually turned out that the rich text control I
> was using, which was written in C++, wasn't able to handle a large
> buffer gracefully.  The parsing code in Python did just fine and
> didn't contribute to the lag issue at all.

The opposite decision, the same result. Performance was *good enough*.
With Gypsum, my early performance problems were almost completely
solved by properly handling the expose-event and only painting the
parts that changed (I don't use a rich text control, I use a
GTK2.DrawingArea). Text processing of something that's come over a
network is seldom a problem; if it were, we'd see noticeably slower
downloads over HTTPS than HTTP, and that just doesn't happen. I think
(though I can't prove) that crypto written in C is probably more
expensive than ANSI parsing written in Python.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Ian Kelly
On Sat, Jan 5, 2013 at 8:57 AM, Chris Angelico  wrote:
> You miss my point, though. I went for simple Pythonic code, and never
> measured its performance, on the expectation that it's "good enough".
> Written in C, the state machine is probably WAY faster than splitting
> and then iterating. My C++ MUD client uses code similar to that to
> parse TELNET and ANSI codes from a stream of bytes in a socket (and
> one of its "states" is that there's no more data available, so wait on
> the socket); the rewrite in a high level language divides the string
> on "\xFF" for TELNET and "\x1B" for ANSI, working them separately, and
> then afterward splits on "\n" to divide into lines. The code's much
> less convoluted, it's easier to test different parts (because I can
> simply call the ANSI parser with a block of text), and on a modern
> computer, you can't see the performance difference (since you spend
> most of your time waiting for socket data anyway).

Anecdotally and somewhat off-topic, when I wrote my own MUD client in
Python, I implemented both TELNET and ANSI parsing in Python using a
state machine processing one byte at a time (actually two state
machines - one at the protocol layer and one at the client layer; the
telnet module is a modified version of the twisted.conch.telnet
module).  I was worried that the processing would be too slow in
Python.  When I got it running, it turned out that there was a
noticeable lag between input being received and displayed.  But when I
profiled the issue it actually turned out that the rich text control I
was using, which was written in C++, wasn't able to handle a large
buffer gracefully.  The parsing code in Python did just fine and
didn't contribute to the lag issue at all.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reduce expression to test sublist

2013-01-05 Thread chaouche yacine
Because reduce doesn't do what you want. You'd want "all".

L1 = [1,2,3]
L2 = ["A1","B2","C3",1,2,3]
print all((x in L2 for x in L1)) # prints True
L3 = ["A1","B2","C3"]
print all((x in L2 for x in L3)) # prints True




- Original Message -
From: Asim 
To: python-list@python.org
Cc: 
Sent: Saturday, January 5, 2013 7:25 PM
Subject: reduce expression to test sublist

Hi All

The following reduce expression checks if every element of list lst1 is present 
in list lst2.  It works as expected for integer lists but for lists of strings, 
it always returns False.

   reduce( lambda x,y: (x in lst2) and (y in lst2), lst1)

Moreover, for the lists of strings the following for-loop gives correct results 
when the above reduce expression doesn't.

   isSublist = True
   for i in lst1:
      isSublist = isSublist and (i in lst2)
      if not isSublist:
         isSublist = False
         break


Can someone help me understand why?

Asim
-- 
http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python wiki gone?

2013-01-05 Thread Andrew Berg
On 2013.01.05 13:07, Lee Harr wrote:
> When I go to wiki.python.org I get redirected to
> http://wiki.python.org/moin/
> which is 404 Not Found.
There's a security issue with moinmoin. The Python wiki is not the only
wiki offline for this reason.
-- 
CPython 3.3.0 | Windows NT 6.2.9200.16461 / FreeBSD 9.1-RELEASE
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pygame - importing GL - very bad...

2013-01-05 Thread someone

On 01/05/2013 02:27 PM, Chris Angelico wrote:

On Sun, Jan 6, 2013 at 12:06 AM, someone  wrote:



In any case I think we understand each other.


That's one of the links I just posted :) It's not just a naming
difference, though. With Pascal's pass-by-reference semantics, this
code would act differently:

def foo(x):
   x = 5

a = 2
foo(a)
print(a)

Python prints 2, because the assignment to x just rebinds the name
inside foo. True pass-by-reference actually changes the caller's
variable. C can achieve this by means of pointers; in Python, you can


I thought that python also used "true" pass-by-reference, although I 
haven't figured out exactly when I have this problem. I can just see 
that sometimes I get this problem and then I need to copy the variable, 
if I don't want the original data of the variable to be overwritten...



pass and mutate a list, thus:

def foo(x):
   x[0] = 5 # Dereference the pointer, kinda

x=[None] # Declare a pointer variable, ish
x[0] = 2
foo(x) # Don't forget to drop the [0] when passing the pointer to
another function
print(x[0]) # Prints 5. See? We have pass-by-reference!


Yes, something like this has happened to me in my python code... Not 
sure if my example was exactly like this, but I remember something where 
I found this to be a problem that I had to fix.



But otherwise, rebinding names in the function has no effect on
anything outside. Among other things, this guarantees that, in any


hmm. ok So it's not true pass-by-reference like I thought... That's 
interesting.



situation, a name referencing an object can be perfectly substituted
for any other name referencing the same object, or any other way of
accessing the object.

def foo(lst):
   lst[0]=len(lst)

x = [10,20,30]
y = x
foo(x) # These two...
foo(y) # ... are identical!


This is something I've experienced from my own coding, I think...


This is a philosophy that extends through the rest of the language. A
function returning a list can be directly dereferenced, as can a list
literal:

def foo():
   return [0,1,4,9,16]

print( ["Hello","world!","Testing","Testing","One","Two","Three"][foo()[2]] )


That prints out "One"... I think I understand - that's interesting too...


This is a flexibility and power that just doesn't exist in many older
languages (C and PHP, I'm looking at you). Object semantics make more
sense than any other system for a modern high level language, which is
why many of them do things that way.


I agree, that I think python is really great and it's fast to do 
something useful. Not sure I still understand exactly all aspects of 
this pass-by-value and by-references, but in any case I know enough to 
watch out for this problem and once I see I have a problem, I can also 
take care of it and solve it by making a copy. I think maybe after 3-6-9 
months more of working with python, I should be fully confident with 
this. Thanks for taking the time to explain a bit of this to me...



--
http://mail.python.org/mailman/listinfo/python-list


Re: import of ttk

2013-01-05 Thread Verde Denim
On 01/04/2013 11:39 PM, Terry Reedy wrote:
> On 1/4/2013 11:02 PM, Verde Denim wrote:
>> In reading through one of the learning articles, I have a bit of code
>> that imports ttk, but I apparently don't have this installed. I've
>> looked up the svn checkout for python-tk, and have checked it out
>> (read-only), but still get the same error. I'm running 2.6.6 python, if
>> that helps.
> 
> Show the line of code that did not work and the traceback. What system
> are you running on and what tcl/tk installation does it have? ttk is
> included with any 8.5 installation. tile is often included with 8.4
> installations and should be picked up as well.
> 
>  The article I'm looking at is here -
>> http://www.zetcode.com/gui/tkinter/introduction/
> 
> 
The line is -
16 from ttk import Frame, Button, Style

$ python tkinter_tut1.py
Traceback (most recent call last):
  File "tkinter_tut1.py", line 16, in 
from ttk import Frame, Button, Style
ImportError: No module named ttk

I'm running on Debian Squeeze, and do show both 8.4 and 8.5 of tcl
-- 
http://mail.python.org/mailman/listinfo/python-list


python wiki gone?

2013-01-05 Thread Lee Harr

Have I just happened across wiki.python.org at a bad time,
or is the wiki gone?

When I go to wiki.python.org I get redirected to
http://wiki.python.org/moin/
which is 404 Not Found.

  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reduce expression to test sublist

2013-01-05 Thread Dave Angel
On 01/05/2013 01:25 PM, Asim wrote:
> Hi All
>
> The following reduce expression checks if every element of list lst1 is 
> present in list lst2.  It works as expected for integer lists but for lists 
> of strings, it always returns False.
>
>reduce( lambda x,y: (x in lst2) and (y in lst2), lst1)
>
> Moreover, for the lists of strings the following for-loop gives correct 
> results when the above reduce expression doesn't.
>
>isSublist = True
>for i in lst1:
>   isSublist = isSublist and (i in lst2)
>   if not isSublist:
>  isSublist = False
>  break
>
>
> Can someone help me understand why?
>
> Asim
reduce only makes sense if the value you're reducing to is of the same
type as the elements of the list you're iterating over.  Since your
lambda expression returns a boolean (True or False), it'll seem to work
on some lists of ints.  That's just a coincidence since the bools are
compatible with ints, and maybe you've got a 0 or 1 in the list.  But if
your list has only strings, then True will never be that list.

If you're trying to make a faster loop, then I suggest you look into set
differences.  Turn both lists into sets, and subtract them.   Something
like (untested):

   result =  not bool( set(lst1) - set(lst2) )



-- 

DaveA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Tim Chase

On 01/05/13 11:24, Tim Chase wrote:

 I don't know how this version times out:

import re
r = re.compile(r"[-+](\d+)([^-+]*)")
def modify(m):
result = m.group(2)[int(m.group(1)):]
return result


Doh, I intended to change this after testing, making it just

  returm m.group(2)[int(m.group(1)):]

rather than expending an intermediate variable I used for testing

-tkc


--
http://mail.python.org/mailman/listinfo/python-list


reduce expression to test sublist

2013-01-05 Thread Asim
Hi All

The following reduce expression checks if every element of list lst1 is present 
in list lst2.  It works as expected for integer lists but for lists of strings, 
it always returns False.

   reduce( lambda x,y: (x in lst2) and (y in lst2), lst1)

Moreover, for the lists of strings the following for-loop gives correct results 
when the above reduce expression doesn't.

   isSublist = True
   for i in lst1:
  isSublist = isSublist and (i in lst2)
  if not isSublist:
 isSublist = False
 break


Can someone help me understand why?

Asim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Tim Chase

On 01/05/13 02:35, Sia wrote:

I have strings such as:

tA.-2AG.-2AG,-2ag
or
.+3ACG.+5CAACG.+3ACG.+3ACG

The plus and minus signs are always followed by a number (say, i). I want 
python to find each single plus or minus, remove the sign, the number after it 
and remove i characters after that. So the two strings above become:

tA..,
and
...


With the same caveat as Frank posted about the second one being 
"" (4 dots), I don't know how this version times out:


  import re
  r = re.compile(r"[-+](\d+)([^-+]*)")
  def modify(m):
  result = m.group(2)[int(m.group(1)):]
  return result
  for test, expected in (
  ("tA.-2AG.-2AG,-2ag", "tA..,"),
  (".+3ACG.+5CAACG.+3ACG.+3ACG", ""),
  ):
  s = r.sub(modify, test)
  print "%r -> %r (%r)" % (
  test, s, expected
  )
  assert s == expected, "Nope"

(it passes the tests as modified to "")

-tkc





--
http://mail.python.org/mailman/listinfo/python-list


Re: Yet another attempt at a safe eval() call

2013-01-05 Thread matt . newville
On Saturday, January 5, 2013 8:17:16 AM UTC-8, Oscar Benjamin wrote:
> On 5 January 2013 16:01, Chris Angelico  wrote:
> 
> > On Sun, Jan 6, 2013 at 2:56 AM, Oscar Benjamin
> 
> >  wrote:
> 
> >> On 4 January 2013 15:53, Grant Edwards  wrote:
> 
> >>> On 2013-01-04, Steven D'Aprano  
> >>> wrote:
> 
>  On Thu, 03 Jan 2013 23:25:51 +, Grant Edwards wrote:
> 
> 
> 
>  * But frankly, you should avoid eval, and write your own mini-integer
> 
>    arithmetic evaluator which avoids even the most remote possibility
> 
>    of exploit.
> 
> >>>
> 
> >>> That's obviously the "right" thing to do.  I suppose I should figure
> 
> >>> out how to use the ast module.
> 
> >>
> 
> >> Someone has already created a module that does this called numexpr. Is
> 
> >> there some reason why you don't want to use that?
> 
> >>
> 
> > import numexpr
> 
> > numexpr.evaluate('2+4*5')
> 
> >> array(22, dtype=int32)
> 
> > numexpr.evaluate('2+a*5', {'a':4})
> 
> >> array(22L)
> 
> >
> 
> > Is that from PyPI? It's not in my Python 3.3 installation. Obvious
> 
> > reason not to use it: Unaware of it. :)
> 
> 
> 
> My apologies. I should have at least provided a link:
> 
> http://code.google.com/p/numexpr/
> 
> 
> 
> I installed it from the ubuntu repo under the name python-numexpr. It
> 
> is also on PyPI:
> 
> http://pypi.python.org/pypi/numexpr
> 
> 
> 
> numexpr is a well established project intended primarily for memory
> 
> and cache efficient computations over large arrays of data. Possibly
> 
> as a side effect, it can also be used to evaluate simple algebraic
> 
> expressions involving ordinary scalar variables.
> 
> 
> 
> 
> 
> Oscar

The asteval module http://pypi.python.org/pypi/asteval/0.9 and
http://newville.github.com/asteval/  might be another alternative.  It's not as 
fast as numexpr, but a bit more general. It uses the ast module to "compile" an 
expression into the AST, then walks through that, intercepting Name nodes and 
using a flat namespace of variables.  It disallows imports and does not support 
all python constructs, but it is a fairly complete in supporting python syntax.

It makes no claim at actually being safe from malicious attack, but should be 
safer than a straight eval(), and prevent accidental problems when evaluating 
user-input as code.  If anyone can find exploits within it, I'd be happy to try 
to fix them.

--Matt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet another attempt at a safe eval() call

2013-01-05 Thread Oscar Benjamin
On 5 January 2013 16:01, Chris Angelico  wrote:
> On Sun, Jan 6, 2013 at 2:56 AM, Oscar Benjamin
>  wrote:
>> On 4 January 2013 15:53, Grant Edwards  wrote:
>>> On 2013-01-04, Steven D'Aprano  wrote:
 On Thu, 03 Jan 2013 23:25:51 +, Grant Edwards wrote:

 * But frankly, you should avoid eval, and write your own mini-integer
   arithmetic evaluator which avoids even the most remote possibility
   of exploit.
>>>
>>> That's obviously the "right" thing to do.  I suppose I should figure
>>> out how to use the ast module.
>>
>> Someone has already created a module that does this called numexpr. Is
>> there some reason why you don't want to use that?
>>
> import numexpr
> numexpr.evaluate('2+4*5')
>> array(22, dtype=int32)
> numexpr.evaluate('2+a*5', {'a':4})
>> array(22L)
>
> Is that from PyPI? It's not in my Python 3.3 installation. Obvious
> reason not to use it: Unaware of it. :)

My apologies. I should have at least provided a link:
http://code.google.com/p/numexpr/

I installed it from the ubuntu repo under the name python-numexpr. It
is also on PyPI:
http://pypi.python.org/pypi/numexpr

numexpr is a well established project intended primarily for memory
and cache efficient computations over large arrays of data. Possibly
as a side effect, it can also be used to evaluate simple algebraic
expressions involving ordinary scalar variables.


Oscar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random List Loop?!

2013-01-05 Thread Oscar Benjamin
On 5 January 2013 15:47, Christian Gabriel  wrote:
> Hi
>
> I have tried now for ages to make a loop that does the following:
>
> Makes a new list with 9 random values, from 9 different lists, with 9 
> elements.
>
> And makes sure that none of the elements repeat!
>
> Is there anyone that can help, with a very simple solution??

I'm sure that there is a simple solution but I don't fully understand
your problem could you perhaps provide an example with actual numbers
(perhaps use 3 instead of 9 so it's easier to follow)?

In any case I suspect that you want something involving range() and
random.shuffle() if that helps.


Oscar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random List Loop?!

2013-01-05 Thread Chris Angelico
On Sun, Jan 6, 2013 at 2:47 AM, Christian Gabriel
 wrote:
> Hi
>
> I have tried now for ages to make a loop that does the following:
>
> Makes a new list with 9 random values, from 9 different lists, with 9 
> elements.
>
> And makes sure that none of the elements repeat!
>
> Is there anyone that can help, with a very simple solution??

Sounds like a homework question to me.

You've tried. What code have you come up with, and to what extent does
it fall short of your goal?

The nine different lists - do they have unique elements?

Are you able to use sets? (If you haven't been taught what a set is,
the answer's probably no.)

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet another attempt at a safe eval() call

2013-01-05 Thread Chris Angelico
On Sun, Jan 6, 2013 at 2:56 AM, Oscar Benjamin
 wrote:
> On 4 January 2013 15:53, Grant Edwards  wrote:
>> On 2013-01-04, Steven D'Aprano  wrote:
>>> On Thu, 03 Jan 2013 23:25:51 +, Grant Edwards wrote:
>>>
>>> * But frankly, you should avoid eval, and write your own mini-integer
>>>   arithmetic evaluator which avoids even the most remote possibility
>>>   of exploit.
>>
>> That's obviously the "right" thing to do.  I suppose I should figure
>> out how to use the ast module.
>
> Someone has already created a module that does this called numexpr. Is
> there some reason why you don't want to use that?
>
 import numexpr
 numexpr.evaluate('2+4*5')
> array(22, dtype=int32)
 numexpr.evaluate('2+a*5', {'a':4})
> array(22L)

Is that from PyPI? It's not in my Python 3.3 installation. Obvious
reason not to use it: Unaware of it. :)

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Chris Angelico
On Sun, Jan 6, 2013 at 2:38 AM, Roy Smith  wrote:
> In article ,
>  Chris Angelico  wrote:
>
>> it may or may not run faster than the explicit state machine,
>
> You got me by a factor of 3 or 4.  Not bad.

You miss my point, though. I went for simple Pythonic code, and never
measured its performance, on the expectation that it's "good enough".
Written in C, the state machine is probably WAY faster than splitting
and then iterating. My C++ MUD client uses code similar to that to
parse TELNET and ANSI codes from a stream of bytes in a socket (and
one of its "states" is that there's no more data available, so wait on
the socket); the rewrite in a high level language divides the string
on "\xFF" for TELNET and "\x1B" for ANSI, working them separately, and
then afterward splits on "\n" to divide into lines. The code's much
less convoluted, it's easier to test different parts (because I can
simply call the ANSI parser with a block of text), and on a modern
computer, you can't see the performance difference (since you spend
most of your time waiting for socket data anyway).

But it's gratifying to know that the obvious and brief way to do
things is fast too :)

>> but IMHO it's a lot clearer to read a split() than something
>> that changes state when a particular character is found.
>
> Maybe.  But being familiar with state machines is still a handy skill.
> DNA sequence analysis has lots of problems like "find a start codon
> which is within about 50 bases of a binding site, and then copy
> everything up until you find a stop codon".  Things like that often map
> well to state machines.  Especially if you're trying to do it in
> parallel in all three reading frames.

Sure. And if you're working with petabytes of data, these
considerations become fairly important. When that happens, you start
rewriting your algorithms in C, or using Cython, or something; at very
least, you start rewriting clear and simple algorithms into more
complex ones. But all this happens *after* the code has been tested
and proven. All the rewrites can be verified as being identical to
their reference implementations; you can test one piece at a time as
you change them. It's ever so much easier to work that way.

At work, we had one employee whose code was, shall we say,
less than stellar. At one point, he embarked on a months-long rewrite
of one of his modules; meanwhile, I was unable to adequately test code
that called on it. Once the rewrite was finally complete, I discovered
myriad bugs in my own code, ones that would have been found and fixed
instantly if I'd had even a slow version of the code to work against.
Starting with something you can easily debug helps enormously with
that, because debugging doesn't demand mega-TPS throughput.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random List Loop?!

2013-01-05 Thread Roy Smith
In article ,
 Christian Gabriel  wrote:

> Hi
> 
> I have tried now for ages to make a loop that does the following:
> 
> Makes a new list with 9 random values, from 9 different lists, with 9 
> elements.
> 
> And makes sure that none of the elements repeat! 
> 
> Is there anyone that can help, with a very simple solution??
> 
> Best
> 
> Christian

You want random.sample()

http://docs.python.org/2/library/random.html#random.sample
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet another attempt at a safe eval() call

2013-01-05 Thread Oscar Benjamin
On 4 January 2013 15:53, Grant Edwards  wrote:
> On 2013-01-04, Steven D'Aprano  wrote:
>> On Thu, 03 Jan 2013 23:25:51 +, Grant Edwards wrote:
>>
>> * But frankly, you should avoid eval, and write your own mini-integer
>>   arithmetic evaluator which avoids even the most remote possibility
>>   of exploit.
>
> That's obviously the "right" thing to do.  I suppose I should figure
> out how to use the ast module.

Someone has already created a module that does this called numexpr. Is
there some reason why you don't want to use that?

>>> import numexpr
>>> numexpr.evaluate('2+4*5')
array(22, dtype=int32)
>>> numexpr.evaluate('2+a*5', {'a':4})
array(22L)


Oscar
-- 
http://mail.python.org/mailman/listinfo/python-list


Random List Loop?!

2013-01-05 Thread Christian Gabriel
Hi

I have tried now for ages to make a loop that does the following:

Makes a new list with 9 random values, from 9 different lists, with 9 elements.

And makes sure that none of the elements repeat! 

Is there anyone that can help, with a very simple solution??

Best

Christian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Couting the number of lines of code of a python program

2013-01-05 Thread Roy Smith
In article ,
 Dave Angel  wrote:

> On 01/05/2013 10:17 AM, chaouche yacine wrote:
> > 
> 
> 
> >
> > Here is my implementation :
> >
> > defcount_loc(lines):nb_lines =0docstring =Falseforline inlines:line 
> > =line.strip()ifline ==""\ orline.startswith("#")\ ordocstring 
> > andnot(line.startswith('"""')orline.startswith("'''"))\ 
> > or(line.startswith("'''")andline.endswith("'''")andlen(line)>3)\ 
> > or(line.startswith('"""')andline.endswith('"""')andlen(line)>3):continue# 
> > this is either a starting or ending 
> > docstringelifline.startswith('"""')orline.startswith("'''"):docstring 
> > =notdocstring continueelse:nb_lines +=1returnnb_lines
> 
> Wow, this is thoroughly garbled.  Please configure your email (yahoo?)
> to use text mode email, to not delete spaces, to honor newlines, etc.

Nice to know that wasn't just another case of my using an antiquated 
news reader :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Couting the number of lines of code of a python program

2013-01-05 Thread chaouche yacine
Sorry, I don't know what went wrong, here is another paste (hopefully this will 
work this time). If you prefer, this a link anchor to the function 
https://www.assembla.com/code/tahar/subversion/nodes/tahar.py?rev=8#ln340

def count_loc(lines):
    nb_lines  = 0
    docstring = False
    for line in lines:
    line = line.strip()

    if line == "" \
   or line.startswith("#") \
   or docstring and not (line.startswith('"""') or 
line.startswith("'''"))\
   or (line.startswith("'''") and line.endswith("'''") and len(line) 
>3)  \
   or (line.startswith('"""') and line.endswith('"""') and len(line) 
>3) :
    continue
    
    # this is either a starting or ending docstring
    elif line.startswith('"""') or line.startswith("'''"):
    docstring = not docstring
    continue

    else:
    nb_lines += 1

    return nb_lines





- Original Message -
From: Chris Angelico 
To: python-list@python.org
Cc: 
Sent: Saturday, January 5, 2013 4:25 PM
Subject: Re: Couting the number of lines of code of a python program

On Sun, Jan 6, 2013 at 2:17 AM, chaouche yacine
 wrote:
> defcount_loc(lines):nb_lines =0docstring =Falseforline inlines:line 
> =line.strip()ifline ==""\ orline.startswith("#")\ ordocstring 
> andnot(line.startswith('"""')orline.startswith("'''"))\ 
> or(line.startswith("'''")andline.endswith("'''")andlen(line)>3)\ 
> or(line.startswith('"""')andline.endswith('"""')andlen(line)>3):continue# 
> this is either a starting or ending 
> docstringelifline.startswith('"""')orline.startswith("'''"):docstring 
> =notdocstring continueelse:nb_lines +=1returnnb_lines

Ow-what? Something's gone wrong with all your whitespace, I think...
can you paste again please?

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Roy Smith
In article ,
 Chris Angelico  wrote:

> it may or may not run faster than the explicit state machine,

Hmmm, hard to say.  Both are O(n), but yours makes several more copies 
of the data than mine (the string addition, the replace(), the split(), 
the string slicing).  We both make copies as we put fragments into a 
list, and when we do the join().
  
On the other hand, yours does all that inside the library, which is 
generally faster than random python code.

Let's see:

My way:
real0m2.097s
user0m2.078s
sys 0m0.016s

Your way:
real0m0.649s
user0m0.622s
sys 0m0.025s

You got me by a factor of 3 or 4.  Not bad.  And not terribly 
surprising.  Once you've got things to the same O() group, pushing as 
much data manipulation as you can down into the library is usually a 
pretty effective optimization technique.

> but IMHO it's a lot clearer to read a split() than something
> that changes state when a particular character is found.

Maybe.  But being familiar with state machines is still a handy skill.  
DNA sequence analysis has lots of problems like "find a start codon 
which is within about 50 bases of a binding site, and then copy 
everything up until you find a stop codon".  Things like that often map 
well to state machines.  Especially if you're trying to do it in 
parallel in all three reading frames.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Couting the number of lines of code of a python program

2013-01-05 Thread Dave Angel
On 01/05/2013 10:17 AM, chaouche yacine wrote:
> 


>
> Here is my implementation :
>
> defcount_loc(lines):nb_lines =0docstring =Falseforline inlines:line 
> =line.strip()ifline ==""\ orline.startswith("#")\ ordocstring 
> andnot(line.startswith('"""')orline.startswith("'''"))\ 
> or(line.startswith("'''")andline.endswith("'''")andlen(line)>3)\ 
> or(line.startswith('"""')andline.endswith('"""')andlen(line)>3):continue# 
> this is either a starting or ending 
> docstringelifline.startswith('"""')orline.startswith("'''"):docstring 
> =notdocstring continueelse:nb_lines +=1returnnb_lines

Wow, this is thoroughly garbled.  Please configure your email (yahoo?)
to use text mode email, to not delete spaces, to honor newlines, etc.


>
>
> - Original Message -
> From: Chris Angelico 
> To: python-list@python.org
Why is the quoted part *after* your message?   Please don't top-post on
this list (or most of them).  It gets too garbled after one or two
generations.



-- 

DaveA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Couting the number of lines of code of a python program

2013-01-05 Thread Chris Angelico
On Sun, Jan 6, 2013 at 2:17 AM, chaouche yacine
 wrote:
> defcount_loc(lines):nb_lines =0docstring =Falseforline inlines:line 
> =line.strip()ifline ==""\ orline.startswith("#")\ ordocstring 
> andnot(line.startswith('"""')orline.startswith("'''"))\ 
> or(line.startswith("'''")andline.endswith("'''")andlen(line)>3)\ 
> or(line.startswith('"""')andline.endswith('"""')andlen(line)>3):continue# 
> this is either a starting or ending 
> docstringelifline.startswith('"""')orline.startswith("'''"):docstring 
> =notdocstring continueelse:nb_lines +=1returnnb_lines

Ow-what? Something's gone wrong with all your whitespace, I think...
can you paste again please?

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Couting the number of lines of code of a python program

2013-01-05 Thread chaouche yacine
The idea started off as a volumetric information of my projects, but evolved to 
a sort of code browser that would display classes, methods and functions in a 
tree-like structure, and now I mostly want to use it with other people's code 
as a way to have the big picture. So I would say that it is used both for my 
programs (to get a feeling of their size) as much as it is used for others' 
code.

> But counting lines of code is a hairy thing to do. Do blank lines,
> comments, and multi-line strings count?

The way I implmented it, they do not, particulary docstrings (even though it 
seems that many people think docstrings are actual code). My opinion on 
docstrings is that they're not instructions. I want to know how many lines of 
instructions a program has. Comments, blank lines and docstrings are not 
intructions.

Here is my implementation :

defcount_loc(lines):nb_lines =0docstring =Falseforline inlines:line 
=line.strip()ifline ==""\ orline.startswith("#")\ ordocstring 
andnot(line.startswith('"""')orline.startswith("'''"))\ 
or(line.startswith("'''")andline.endswith("'''")andlen(line)>3)\ 
or(line.startswith('"""')andline.endswith('"""')andlen(line)>3):continue# this 
is either a starting or ending 
docstringelifline.startswith('"""')orline.startswith("'''"):docstring 
=notdocstring continueelse:nb_lines +=1returnnb_lines



- Original Message -
From: Chris Angelico 
To: python-list@python.org
Cc: 
Sent: Saturday, January 5, 2013 3:09 PM
Subject: Re: Couting the number of lines of code of a python program

On Sun, Jan 6, 2013 at 12:55 AM, chaouche yacine
 wrote:
> The
>  problem is that I'm using the inspect module, because it provides a
> nice function inspect.getsourcelines that takes a python object and
> return its number of lines of code. BUT, it works on live objects, that
> means one has to first import the module he wants to process, and this
> can have side effects (example : GUI programs).

If you're using this entirely on your own code, one good way to solve
the problem is to make your code always importable. Protect your
top-level code with "if __name__=='__main__':" (and possibly put it
into a function main() if that simplifies your code counting), and you
should then be able to import it as-is, and all you'll do is define ams and 
bunch of functions/classes.

But counting lines of code is a hairy thing to do. Do blank lines,
comments, and multi-line strings count?

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Chris Angelico
On Sun, Jan 6, 2013 at 2:03 AM, Roy Smith  wrote:
> That's why I chose to split this where I did.  It was where the scan
> direction changed.

Ah, good point. In any case, this is a fairly simple and clear way of
doing things; it may or may not run faster than the explicit state
machine, but IMHO it's a lot clearer to read a split() than something
that changes state when a particular character is found.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Roy Smith
In article ,
 Chris Angelico  wrote:

> On Sun, Jan 6, 2013 at 1:30 AM, Roy Smith  wrote:
> > In article ,
> >  Chris Angelico  wrote:
> >
> >> result = "".join([x[int(x[0])+1:] for x in 
> >> ("0"+s).replace("-","+").split("+")])
> >
> > That's exceedingly clever.  But bordering on line noise.  At the very
> > least, I would break it up into a couple of lines to make it easier to
> > understand (plus you can print out the intermediate values to see what's
> > going on):
> >
> > chunks = ("0"+s).replace("-","+").split("+")
> > result = "".join([x[int(x[0])+1:] for x in chunks]
> 
> Sure. You can always split a one-liner to taste, doesn't much matter
> where.

Well, there are better and worse places to split things.  Consider these 
three statements:

result = f1().f2().f3().f4().f5()
result = f1(f2.f3(f4().f5()))
result = f1(f2(3(f4(f5()

Same number of function calls, but the middle one is clearly the most 
difficult to understand.  The reason is because the scan direction keeps 
changing.  The first one is strictly left-to-right.  The last one is 
strictly inside-to-outside.  The middle one is all over the place.

That's why I chose to split this where I did.  It was where the scan 
direction changed.

Readability matters.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Chris Angelico
On Sun, Jan 6, 2013 at 1:30 AM, Roy Smith  wrote:
> In article ,
>  Chris Angelico  wrote:
>
>> result = "".join([x[int(x[0])+1:] for x in 
>> ("0"+s).replace("-","+").split("+")])
>
> That's exceedingly clever.  But bordering on line noise.  At the very
> least, I would break it up into a couple of lines to make it easier to
> understand (plus you can print out the intermediate values to see what's
> going on):
>
> chunks = ("0"+s).replace("-","+").split("+")
> result = "".join([x[int(x[0])+1:] for x in chunks]

Sure. You can always split a one-liner to taste, doesn't much matter
where. You could split it majorly into half a dozen lines if you want,
doesn't make a lot of diff. It'll work the same way :)

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows Installer Error

2013-01-05 Thread matttwall
On Saturday, January 5, 2013 8:30:39 AM UTC-6, matt...@gmail.com wrote:
> I am running on Windows 7 Professional x64 with latest service pack and I 
> cannot get Python to install. I run the python-3.2.1.msi, and after I select 
> the installation directory, I get a popup that says "There is a problem with 
> this Windows Installer package. A DLL required for this install to complete 
> could not be run. Contact your support personnel or package vendor". 2.7.3, 
> amd64, and older packages all do the exact same thing.

NVM, I solved it just this very moment. I found this topic 
http://superuser.com/questions/478631/dll-could-not-be-run-for-msi-installers. 
It turns out I had to go to my Temp directory and give Full Control to the 
Everyone group. No idea why the MSI wouldn't have admin rights.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Roy Smith
In article ,
 Chris Angelico  wrote:

> result = "".join([x[int(x[0])+1:] for x in 
> ("0"+s).replace("-","+").split("+")])

That's exceedingly clever.  But bordering on line noise.  At the very 
least, I would break it up into a couple of lines to make it easier to 
understand (plus you can print out the intermediate values to see what's 
going on):

chunks = ("0"+s).replace("-","+").split("+")
result = "".join([x[int(x[0])+1:] for x in chunks]
-- 
http://mail.python.org/mailman/listinfo/python-list


Windows Installer Error

2013-01-05 Thread matttwall
I am running on Windows 7 Professional x64 with latest service pack and I 
cannot get Python to install. I run the python-3.2.1.msi, and after I select 
the installation directory, I get a popup that says "There is a problem with 
this Windows Installer package. A DLL required for this install to complete 
could not be run. Contact your support personnel or package vendor". 2.7.3, 
amd64, and older packages all do the exact same thing. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Roy Smith
In article ,
 Sia  wrote:

> I have strings such as:
> 
> tA.-2AG.-2AG,-2ag
> or
> .+3ACG.+5CAACG.+3ACG.+3ACG

Some kind of DNA binding site?

A couple of questions.  Are the numbers always single digits?  How much 
data is there?  Are we talking a few hundred 20-character strings, or 
all of Genbank?

> The plus and minus signs are always followed by a number (say, i). I want 
> python to find each single plus or minus, remove the sign, the number after 
> it and remove i characters after that. So the two strings above become:
> 
> tA..,
> and
> ...

If I follow your description properly, the last output should be "" 
(4 dots), right?  This looks like it should work.  I'm sure there's more 
efficient ways to do it, but for small inputs, this should be ok.˜

The general pattern here is a state machine.  It's a good pattern to 
learn if you're going to be doing any kind of sequence analysis.  See, 
for example, http://en.wikipedia.org/wiki/State_machine.

# Build up the new string as a list (for efficiency)

new = []

# Keep track of what state we're in.  The three possible states 

# are 1) scanning for a region to be deleted, 2) looking for the

# number, and 3) reading past the letters to be deleted.

SCANNING = 1
NUMBER = 2
DROPPING = 3
state = SCANNING

# If we are in state DROPPING, dropcount is the number of   

# letters remaining to be dropped.  

dropcount = 0

old = '.+3ACG.+5CAACG.+3ACG.+3ACG'
for c in old:
if state == SCANNING:
if c in '+-':
state = NUMBER
else:
new.append(c)

elif state == NUMBER:
# Assume the counts are all single digits.  If not, then
# we'll need a 4th state for accumulating the digits.  
dropcount = int(c)
state = DROPPING

else:
assert state == DROPPING
dropcount -= 1
if dropcount == 0:
state = SCANNING

print ''.join(new)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Couting the number of lines of code of a python program

2013-01-05 Thread Chris Angelico
On Sun, Jan 6, 2013 at 12:55 AM, chaouche yacine
 wrote:
> The
>  problem is that I'm using the inspect module, because it provides a
> nice function inspect.getsourcelines that takes a python object and
> return its number of lines of code. BUT, it works on live objects, that
> means one has to first import the module he wants to process, and this
> can have side effects (example : GUI programs).

If you're using this entirely on your own code, one good way to solve
the problem is to make your code always importable. Protect your
top-level code with "if __name__=='__main__':" (and possibly put it
into a function main() if that simplifies your code counting), and you
should then be able to import it as-is, and all you'll do is define a
bunch of functions/classes.

But counting lines of code is a hairy thing to do. Do blank lines,
comments, and multi-line strings count?

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Couting the number of lines of code of a python program

2013-01-05 Thread chaouche yacine
  
Hello.

I'v written a small script that prints the number of lines
 of code of a python program to stdout (by module, function, class and 
method), the sources are available online here  
https://www.assembla.com/code/tahar/subversion/nodes. The readme has an example 
usage as well as a trace of what the script prints.

The
 problem is that I'm using the inspect module, because it provides a 
nice function inspect.getsourcelines that takes a python object and 
return its number of lines of code. BUT, it works on live objects, that 
means one has to first import the module he wants to process, and this 
can have side effects (example : GUI programs).

So my question is
 how can one count the number of lines of code of a python program 
without importing it (static code analysis) ? 

Some people on IRC
 advised me to look for the AST module. Can you give me a little help on
 how to use this module to count the number of lines of code of a 
function/method ?

Thanks in advance for your help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyGreSQL 4.1 released

2013-01-05 Thread D'Arcy J.M. Cain
On Sat, 5 Jan 2013 13:23:55 +0100
Michael Poeltl  wrote:
> no python3 support yet?
> can you tell us when pygresql will be ready for python3?

Hard to say when (we all have day jobs) but
it is planned for version 5.0.  You can track our milestones at
http://trac.vex.net:8000/pgtracker

We will probably get version 4.2 released shortly and then branch 5.x
and start working on Python 3 support.

-- 
D'Arcy J.M. Cain
PyGreSQL Development Group
http://www.PyGreSQL.org IM:da...@vex.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with exam task for college

2013-01-05 Thread Chris Angelico
On Sun, Jan 6, 2013 at 12:14 AM,   wrote:
> that's probably it, how do i solve it?

I'm afraid I can't help you there. Check out the docs for the getkey
function and see if it can be put into non-blocking mode; if not, you
may have to completely change your model. For instance, if I were
writing this sort of game today, I'd probably use a GUI system that
fires an event whenever a key is pressed/released, and then have a
timer-tick for the descent, rather than explicit sleep() calls. But it
depends on your UI facilities.

The LANDER.BAS that I played with - yes, it was written in BASIC - was
fully prompt-driven. To move to the next time unit, you had to answer
all its prompts. Advantage: No need to code a Pause feature.
Disadvantage: The game ended up way too scientific, like D&D combat.
(It's amazing how your party of bumbling characters suddenly become
lightning-fast strategists as soon as initiative is rolled!)

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pygame - importing GL - very bad...

2013-01-05 Thread Chris Angelico
On Sun, Jan 6, 2013 at 12:06 AM, someone  wrote:
> On 01/05/2013 12:47 PM, Chris Angelico wrote:
>> You can find good references on the subject in various
>> places, but call-by-reference as implemented in Pascal simply doesn't
>> exist in most modern languages, because its semantics are way
>> confusing. The name given to this technique varies; here's a couple of
>> links:
>>
>> http://effbot.org/zone/call-by-object.htm
>> http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing
>
> If you don't like calling it "pass-by-reference", perhaps you prefer calling
> it: “call by object reference“...  From:
> http://effbot.org/zone/call-by-object.htm
>
> In any case I think we understand each other.

That's one of the links I just posted :) It's not just a naming
difference, though. With Pascal's pass-by-reference semantics, this
code would act differently:

def foo(x):
  x = 5

a = 2
foo(a)
print(a)

Python prints 2, because the assignment to x just rebinds the name
inside foo. True pass-by-reference actually changes the caller's
variable. C can achieve this by means of pointers; in Python, you can
pass and mutate a list, thus:

def foo(x):
  x[0] = 5 # Dereference the pointer, kinda

x=[None] # Declare a pointer variable, ish
x[0] = 2
foo(x) # Don't forget to drop the [0] when passing the pointer to
another function
print(x[0]) # Prints 5. See? We have pass-by-reference!

But otherwise, rebinding names in the function has no effect on
anything outside. Among other things, this guarantees that, in any
situation, a name referencing an object can be perfectly substituted
for any other name referencing the same object, or any other way of
accessing the object.

def foo(lst):
  lst[0]=len(lst)

x = [10,20,30]
y = x
foo(x) # These two...
foo(y) # ... are identical!

This is a philosophy that extends through the rest of the language. A
function returning a list can be directly dereferenced, as can a list
literal:

def foo():
  return [0,1,4,9,16]

print( ["Hello","world!","Testing","Testing","One","Two","Three"][foo()[2]] )

This is a flexibility and power that just doesn't exist in many older
languages (C and PHP, I'm looking at you). Object semantics make more
sense than any other system for a modern high level language, which is
why many of them do things that way.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with exam task for college

2013-01-05 Thread jeltedeproft
that's probably it, how do i solve it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pylint, was Re: pygame - importing GL - very bad...

2013-01-05 Thread someone

On 01/05/2013 01:49 PM, Jan Riechers wrote:

On 05.01.2013 03:11, someone wrote:
But about the regular expressions (a bit deeper look into that):
Like said of Chris:

[a-z]
defines a "catching group", in this case all ascii lowercase letters
ranging from "a" to "z". If noting else is provided, the rule matches
one letter if there is no range defined by something like:
{} -> Target a range of a match/hit

There are also a
? -> Lazy match
* -> Gready match

[A-Z][0-9]{1,3} means translated:
Look for any uppercase letter in ascii(!) (not "öäü" or similiar)
ranging from "A" to "Z".

Now look for any digit (2nd catching group) with the addition to satisfy
the rule ONLY if there are at least 1 to 3 digits found.
Note: If there are 4 or more digits - the catching rule is still
satisfied and will provide a match/hit.


Ok, thanks a lot for the elaboration... I think I need to work with it 
myself at some time to be sure of understanding it...



If there is a follow up group, the next evaluation is gone through if
present and so forth. If the expression is satisfied, the match is
returned.

The lazy "?" and greedy "*" matches try to satisfy, as the naming
implies, to match as less or as much of what you have asked for.

For example the regular expression is valid:
0* -> Look for a zero, and be greedy as of how many zeros you want match
which might follow.

Regular expressions don't have to include catching groups in order to work.

But when you use them yourself somehow, its quite simple I think.
I guess you are anyhow busy mangling with pyLint, PEP-Standards and
pyOpenGL - so good luck with that :)


You're right - I'm a bit "overbooked" at the moment - but thanks a lot 
for clarifyring this with the regexps :-)




--
http://mail.python.org/mailman/listinfo/python-list


Re: pygame - importing GL - very bad...

2013-01-05 Thread someone

On 01/05/2013 12:47 PM, Chris Angelico wrote:

C has typed variables, so it's a compile-time error to try to put any
other type into that variable. Python doesn't. That flexibility comes
at the cost of error-catching. There are hybrid systems, but in
general, type declarations imply variable declarations, and that's
something that Python doesn't want. (I'm of the opinion that
declarations aren't such a bad thing; they make some aspects of
scoping easier. However, that's a design decision that Python is as
unlikely to reverse as indentation-defined blocks.)


Understood.


Ok, I'll look forward to that. Recently I had some problems with
pass-by-value vs pass-by-reference. I googled the problem and found that by
default python passes by reference.


No, it doesn't. You can find good references on the subject in various
places, but call-by-reference as implemented in Pascal simply doesn't
exist in most modern languages, because its semantics are way
confusing. The name given to this technique varies; here's a couple of
links:

http://effbot.org/zone/call-by-object.htm
http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing


If you don't like calling it "pass-by-reference", perhaps you prefer 
calling it: “call by object reference“...  From: 
http://effbot.org/zone/call-by-object.htm


In any case I think we understand each other.



--
http://mail.python.org/mailman/listinfo/python-list


Re: pylint, was Re: pygame - importing GL - very bad...

2013-01-05 Thread Jan Riechers

On 05.01.2013 03:11, someone wrote:

On 01/03/2013 12:27 PM, Chris Angelico wrote:

On Thu, Jan 3, 2013 at 10:19 PM, someone  wrote:

Doesn't this "[ ... ]" mean something optional?

What does {2,30}$ mean?

I think $ means that the {2,30} is something in the end of the
sentence...


You can find regular expression primers all over the internet, but to
answer these specific questions: [...] means any of the characters in
the range; the $ means "end of string"; and {2,30} means at least two,
and at most thirty, of the preceding character. So you have to have
one from the first group, then 2-30 from the second, for a total of
3-31 characters in your names.


Got it, thanks!




Just following the discussion which is very interesting, even so when 
not working with OpenGL (which looks like a nightmare with that naming 
space) :)


But about the regular expressions (a bit deeper look into that):
Like said of Chris:

[a-z]
defines a "catching group", in this case all ascii lowercase letters 
ranging from "a" to "z". If noting else is provided, the rule matches 
one letter if there is no range defined by something like:

{} -> Target a range of a match/hit

There are also a
? -> Lazy match
* -> Gready match

[A-Z][0-9]{1,3} means translated:
Look for any uppercase letter in ascii(!) (not "öäü" or similiar) 
ranging from "A" to "Z".


Now look for any digit (2nd catching group) with the addition to satisfy 
the rule ONLY if there are at least 1 to 3 digits found.
Note: If there are 4 or more digits - the catching rule is still 
satisfied and will provide a match/hit.


If there is a follow up group, the next evaluation is gone through if 
present and so forth. If the expression is satisfied, the match is returned.


The lazy "?" and greedy "*" matches try to satisfy, as the naming 
implies, to match as less or as much of what you have asked for.


For example the regular expression is valid:
0* -> Look for a zero, and be greedy as of how many zeros you want match 
which might follow.


Regular expressions don't have to include catching groups in order to work.

But when you use them yourself somehow, its quite simple I think.
I guess you are anyhow busy mangling with pyLint, PEP-Standards and 
pyOpenGL - so good luck with that :)


Jan Riechers

--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with exam task for college

2013-01-05 Thread Chris Angelico
On Sat, Jan 5, 2013 at 11:24 PM,   wrote:
> hy again,thanx, i updated my code with your more efficient approach :), so 
> that possibly resolves problem number 2, but still leaves me with problem 
> n°1, my code is still stuck in the first update of the fuel tank 
> (brandstoftank), for the sake of your easyness i'll paste the code again

Not sure what you mean by "stuck", but is it that scene.kb.getkey()
waits for a key?

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyGreSQL 4.1 released

2013-01-05 Thread Michael Poeltl
no python3 support yet?
can you tell us when pygresql will be ready for python3?

thx
Michael


* D'Arcy J.M. Cain  [2013-01-03 15:05]:
> ---
> Release of PyGreSQL version 4.1
> ---
> 
> It has been a long time coming but PyGreSQL v4.1 has been released.
> 
> It is available at: http://pygresql.org/files/PyGreSQL-4.1.tgz.
> 
> If you are running NetBSD, look in the packages directory under
> databases. There is also a package in the FreeBSD ports collection
> which will probably be updated shortly.
> 
> Please refer to `changelog.txt `_
> for things that have changed in this version.
> 
> Please refer to `readme.txt `_
> for general information.
> 
> This version has been built and unit tested on:
>  - NetBSD
>  - FreeBSD
>  - openSUSE 12.2
>  - Windows 7 with both MinGW and Visual Studio
>  - PostgreSQL 8.4, 9.0 and 9.2 32 and 64bit
>  - Python 2.5, 2.6 and 2.7 32 and 64bit
> 
> -- 
> D'Arcy J.M. Cain
> PyGreSQL Development Group
> http://www.PyGreSQL.org IM:da...@vex.net
> -- 
> http://mail.python.org/mailman/listinfo/python-list

-- 
Michael Poeltl
Computational Materials Physics  voice: +43-1-4277-51409
Univ. Wien, Sensengasse 8/12 fax:   +43-1-4277-9514 (or 9513) 
A-1090 Wien, AUSTRIA   cmp.mpi.univie.ac.at 
---
slackware-13.37 | vim-7.3 | python-3.2.3 | mutt-1.5.21 | elinks-0.12
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with exam task for college

2013-01-05 Thread jeltedeproft
hy again,thanx, i updated my code with your more efficient approach :), so that 
possibly resolves problem number 2, but still leaves me with problem n°1, my 
code is still stuck in the first update of the fuel tank (brandstoftank), for 
the sake of your easyness i'll paste the code again 

from visual import *
import time
import math
import random
from datetime import datetime
import operator 


class lunar_lander(object):
def __init__(self):
scene.title = 'mini star wars'
scene.width = 375
scene.height = 550
scene.center = (0,0)
self.pos = (0,0)
self.axis = 0
self.brandstofmeter_view = brandstofmeter_view()
self.ruimteschip = ruimteschip()
self.view = game_view(self)



def play(self):
t=0
dt=0.01
while t<9:
time.sleep(0.01)
self.brandstofmeter_view.update()
self.ruimteschip.update(dt)
t = t + dt



class game_view(object):
def __init__(self,owner):
autoscale=True
box(pos=( 0, -375, 0), length=500, height=5, width=0, color = 
color.white)
box(pos=(0,375, 0), length=500, height=5, width=0, color = color.white)
box(pos=(-250,0, 0), length=5, height=750, width=0, color = color.white)
box(pos=(250,0, 0), length=5, height=750, width=0, color = color.white)

maan = 
curve(pos=[(-250,-353),(-240,-341),(-210,-354),(-199.5,-374)],color=color.red)
maana = curve(pos=[(-199.5,-374),(-166,-374)],color=color.green)
maanb = 
curve(pos=[(-166,-374),(-140,-357),(-80,-319),(-40,-361),(0,-321),(40,-329),(80,-347)],color=color.red)
maanc = curve(pos=[(80,-347),(140,-347)],color=color.green)
maand = 
curve(pos=[(140,-347),(162,-337),(189.5,-365),(210,-355),(240,-372),(250,-338)],color=color.red)

for i in random.sample(range (-250,250),20):
for j in random.sample(range (-375,375),20):
sterren = points(pos = [i,j,0],size = 2, color=color.white)




class brandstofmeter_view(object):
def __init__(self):
axis = 0
self.pos = (220,345) 
self.meter = box(pos = self.pos, lenght = 25, height = 45,color = 
color.green)

def update (self):
s = scene.kb.getkey()
if (s == "up"):
self.meter.height = self.meter.height - 1





class ruimteschip(object):
def __init__(self):
self.pos = vector(0,330)
self.acceleration = vector(0,-88,0)
self.axis = (1,0,0)
self.hoek = (90*math.pi)/180
self.graden = math.degrees(self.hoek)
self.gas = vector(10 * cos(self.hoek),10 * sin (self.hoek))
self.velocity = vector(0,0,0)
self.angle = (1,0,0)
self.view = ruimteschip_view(self)
self.vlam = self.view.vlam
self.frame = self.view.frame





def update(self,dt):
self.velocity = self.velocity + (self.acceleration * dt)
self.pos = self.pos + self.velocity * dt
a = 0
b = 0
if scene.kb.keys:
a = a + 0.001 
s = scene.kb.getkey()
if (s == "up"):
self.velocity = self.velocity + self.gas
self.vlam.visible = True
b = b + 2
if (s == "left"):
self.gas = rotate(self.gas,angle = math.pi/10, axis = (0,0,1))
(x,y,z) = self.frame.axis
self.frame.axis = (x,y,z-0.1)
if (s == "right") :
self.gas = rotate(self.gas,angle = -(math.pi/10), axis = 
(0,0,1))
(x,y,z) = self.frame.axis
self.frame.axis = (x,y,z+0.1)
if (a == 0):
self.vlam.visible = False

 
if self.pos.x > 250:
self.pos.x = -250
if self.pos.x < -250:
self.pos.x = 250
self.view.update(self)

class ruimteschip_view(object):
def __init__(self,owner):
self.owner = owner
self.frame = frame(pos = owner.pos,axis = owner.axis)
self.motor = curve(frame = 
self.frame,pos=[(0,24.0),(22.0,24.0),(22.0,39.0),(-22.0,39.0),(-22,24),(0,24)])
self.capsule = curve(frame = self.frame,color = color.blue 
,pos=[(0,39),(-3,39),(-9,44),(-12,46),(-18,48),(-22,50),(-18,52),(-12,54),(-9,56),(-3,61),(0,61),(3,59),(9,56),(12,54),(18,52),(22,50),(18,48),(12,46),(9,44),(3,39),(0,39)])
self.poota = curve(frame = self.frame,pos = 
[(-18,24),(-20,24),(-20,0),(-18,0),(-18,24)])
self.pootb = curve(frame = self.frame,pos = 
[(18,24),(20,24),(20,0),(18,0),(18,24)])
self.vlam = curve(frame = self.frame,color = color.orange , 
visible=false,pos = [(0,24.0),(-9.0,14.0),(0,-5.0),(9,14.0),(0,24.0)])

def update(self,owner):
self.frame

Re: Evaluate postgres boolean field

2013-01-05 Thread andydtaylor
Brilliant, thanks guys
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pygame - importing GL - very bad...

2013-01-05 Thread Chris Angelico
On Sat, Jan 5, 2013 at 9:49 PM, someone  wrote:
> Ok, I think you're right. At least I find that C-compilers catches many
> errors/warnings which python don't say anything about. But also C require me
> to define/declarer the types of variables before I use them... OTOH I guess
> I like that python is faster to code in, compared to C...

C has typed variables, so it's a compile-time error to try to put any
other type into that variable. Python doesn't. That flexibility comes
at the cost of error-catching. There are hybrid systems, but in
general, type declarations imply variable declarations, and that's
something that Python doesn't want. (I'm of the opinion that
declarations aren't such a bad thing; they make some aspects of
scoping easier. However, that's a design decision that Python is as
unlikely to reverse as indentation-defined blocks.)

> Ok, I'll look forward to that. Recently I had some problems with
> pass-by-value vs pass-by-reference. I googled the problem and found that by
> default python passes by reference.

No, it doesn't. You can find good references on the subject in various
places, but call-by-reference as implemented in Pascal simply doesn't
exist in most modern languages, because its semantics are way
confusing. The name given to this technique varies; here's a couple of
links:

http://effbot.org/zone/call-by-object.htm
http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New in Python , Need a Mentor

2013-01-05 Thread someone

On 01/02/2013 05:30 PM, Chris Angelico wrote:

On Thu, Jan 3, 2013 at 3:24 AM, Wolfgang Strobl  wrote:

Chris Angelico :

I strongly recommend IDLE - much
better editing/recall facilities than the command-line Python has),
and work through the tutorial:


Well, this is certainly a matter of taste.  I'd recommend using some
small, language independent programmers editor and some modern
distributed version control system  right at the beginning. Put your
code, even the smallest snippets,  under version control, make that a
habit.  Write small doctests for your code from the very beginning. Try
to construct your code so that it works equally well as a module and as
a standalone script   Don't start developing web applications, write
some small utilities for your own needs, first.

Personally, I suggest SciTE and TortoiseHG on Windows, but that too is,
as I said, a matter of taste.


I don't edit code in IDLE, I just use it for interactive work. For
actual script editing, agreed (though I use git rather than hg), but
it really does help to have a way to *very* quickly test a line or two
of code.


I really REALLY like debugging with "eric"...

http://eric-ide.python-projects.org/


--
http://mail.python.org/mailman/listinfo/python-list


Re: pygame - importing GL - very bad...

2013-01-05 Thread Dave Angel
On 01/05/2013 05:49 AM, someone wrote:
> On 01/05/2013 02:30 AM, Dave Angel wrote:
>

>>
>> Function objects are enormously useful, as you get more adept at using
>> Python.
>
> Ok, I'll look forward to that. Recently I had some problems with
> pass-by-value vs pass-by-reference. I googled the problem and found
> that by default python passes by reference.

Pascal has two calling conventions (value and reference).  C always
calls by value.  C++ adds a call by reference, and maybe later C
standards have added it as well.

Python always calls by object.  In fact, one could argue that there are
no values (in the C sense) in Python.  All names, and all attributes,
and all slots in collections, are references to objects.  So when you
call a function, what you're doing is telling the function how to
reference the same object(s).  The usual way to say that is that the
function call binds a new name to an existing object.

If that object is mutable, then perhaps you wanted to do a copy first. 
Or perhaps you didn't.  As you say, you debugged the program to find out.

> I then debugged my program and finally found out that I should make a
> copy (a new object) of the variable, before I passed it to my
> function. And THIS solved my problem. But in C/C++ I think the default
> is to pass by value, so this error in my program was a bit
> unexpected... Anyway, I feel python is a great language for doing
> things much faster than I could possibly do in C/C++.
>
> I also have on my todo-list to take my opengl-program and make it into
> an executable. I mainly sit on a linux-pc but I want to distribute my
> opengl program for windows (which has most users). I've found
> something on google for py2app, cx_Freeze, bbfreeze and Freeze and I
> hope this cross-platform thing does not cause too many problems... I
> tried one of these tools a few weeks ago but I think I only succeeded
> with a very simple hello-world program... Anyway, that's a problem
> I'll investigate in a few months when I think/hope my opengl program
> is finished...
>


-- 

DaveA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pygame - importing GL - very bad...

2013-01-05 Thread someone

On 01/05/2013 02:30 AM, Dave Angel wrote:

from opengl import gl, glu, glut

gl.rotate(...)
gl.clear(gl.COLOR_BUFFER_BIT)


Erhm, that's the same as above. Is that what you meant to write?



No, it's not the same;  here he did not capitalize the function names.
Previously they look like class instantiations.


Ah, you're right. Sorry :-)


Well, I'm sometimes a bit annoyed that python doesn't give as many
warnings/errors as one gets in C - for instance sometimes I copy/paste
and forget to remove the trailing semi-colons.


Trailing semi colons are legal in most cases.  The semi-colon is a
separator between statements, when one wants to put multiple statements
on one line.


However after I began to use pylint and friends, this error will be
caught. Then sometimes I forgot to add () for function calls, which in
C would cause an error by the compiler


Actually no.  In C, a function name without parentheses is also a
function pointer.  Not exactly the same as a function object, though C++
gets a lot closer.  But the real reason C catches that typo is that the
types most likely don't match, depending on what you meant to do with
the return value.


Ok, I think you're right. At least I find that C-compilers catches many 
errors/warnings which python don't say anything about. But also C 
require me to define/declarer the types of variables before I use 
them... OTOH I guess I like that python is faster to code in, compared 
to C...



but which python allows so one can get the object (which maybe is also
a good reason, but at least in the beginning when I learned python,
this was very annoying + confusing to me).



Function objects are enormously useful, as you get more adept at using
Python.


Ok, I'll look forward to that. Recently I had some problems with 
pass-by-value vs pass-by-reference. I googled the problem and found that 
by default python passes by reference. I then debugged my program and 
finally found out that I should make a copy (a new object) of the 
variable, before I passed it to my function. And THIS solved my problem. 
But in C/C++ I think the default is to pass by value, so this error in 
my program was a bit unexpected... Anyway, I feel python is a great 
language for doing things much faster than I could possibly do in C/C++.


I also have on my todo-list to take my opengl-program and make it into 
an executable. I mainly sit on a linux-pc but I want to distribute my 
opengl program for windows (which has most users). I've found something 
on google for py2app, cx_Freeze, bbfreeze and Freeze and I hope this 
cross-platform thing does not cause too many problems... I tried one of 
these tools a few weeks ago but I think I only succeeded with a very 
simple hello-world program... Anyway, that's a problem I'll investigate 
in a few months when I think/hope my opengl program is finished...




--
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Chris Angelico
On Sat, Jan 5, 2013 at 7:35 PM, Sia  wrote:
> I have strings such as:
>
> tA.-2AG.-2AG,-2ag
> or
> .+3ACG.+5CAACG.+3ACG.+3ACG
>
> The plus and minus signs are always followed by a number (say, i). I want 
> python to find each single plus or minus, remove the sign, the number after 
> it and remove i characters after that. So the two strings above become:
>
> tA..,
> and
> ...
>
> How can I do that?

Interesting. Are you guaranteed that there are no other plus or minus
signs? Is the number after the sign just one digit? Assuming the
answers to both are "yes", here's a one-liner:

s=".+3ACG.+5CAACG.+3ACG.+3ACG"

result = "".join([x[int(x[0])+1:] for x in ("0"+s).replace("-","+").split("+")])

Split on either - or +, then trim off that many characters from each
(that's the list comp), then join them back into a string.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Frank Millman

On 05/01/2013 10:35, Sia wrote:

I have strings such as:

tA.-2AG.-2AG,-2ag
or
.+3ACG.+5CAACG.+3ACG.+3ACG

The plus and minus signs are always followed by a number (say, i). I want 
python to find each single plus or minus, remove the sign, the number after it 
and remove i characters after that. So the two strings above become:

tA..,
and
...

How can I do that?
Thanks.



Here is a naive solution (I am sure there are more elegant ones) -

def strip(old_string):
new_string = ''
max = len(old_string)
pos = 0
while pos < max:
char = old_string[pos]
if char in ('-', '+'):
num_pos = pos+1
num_str = ''
while old_string[num_pos].isdigit():
num_str += old_string[num_pos]
num_pos += 1
pos = num_pos + int(num_str)
else:
new_string += old_string[pos]
pos += 1
return new_string

It caters for the possibility that the number following the +/- could be 
greater than 9 - I don't know if you need that.


It works with your examples, except that the second one returns '', 
which I think is correct - there are 4 dots in the original string.


HTH

Frank Millman


--
http://mail.python.org/mailman/listinfo/python-list


Need a specific sort of string modification. Can someone help?

2013-01-05 Thread Sia
I have strings such as:

tA.-2AG.-2AG,-2ag
or
.+3ACG.+5CAACG.+3ACG.+3ACG

The plus and minus signs are always followed by a number (say, i). I want 
python to find each single plus or minus, remove the sign, the number after it 
and remove i characters after that. So the two strings above become:

tA..,
and
...

How can I do that?
Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list