Re: [Tutor] Question on how to do exponents

2012-02-07 Thread Alan Gauld

On 07/02/12 01:01, Nate Lastname wrote:

Exponents ... are **(or ^)


Not quite the ^ operator is a bitwise XOR...

 2^2
0
 2^1
3

pow() is the other way to do exponents.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


[Tutor] Rép. : Re: Issue with a shapefile (ArcGIS) library (pyshp) unpack requires a string argument of length 8

2012-02-07 Thread Simeon Tesfaye
I just realized my first email was not very self explanatory, so let me
start over.
 
My system is Windows XP Professional, with Python 2.5, and the library
I'm experiencing trouble with is pyshp, available (single version for
all systems) here : 
http://code.google.com/p/pyshp/
 
Here is the correct error message I get (I removed my failed attempt at
correcting the library, thanks for pointing that out Dave) :
Traceback (most recent call last):

  File pyshell#3, line 1, in module
rsh=shreader.shapes()
  File C:\Python25\shapefile.py, line 310, in shapes
shapes.append(self.__shape())
  File C:\Python25\shapefile.py, line 222, in __shape
(recNum, recLength) = unpack(2i, f.read(8))
  File C:\Python25\lib\struct.py, line 87, in unpack
return o.unpack(s)
error: unpack requires a string argument of length 8
 
My code can be summarized as that
f=shapefile.Editor(shapefile=C:\Sampler\Shpfiles\ROUTE.shp)
f.line(parts=[[coord[0],[0,0],[10,10]]])
f.record(i put my attributes here) 
f.save('ROUTE')
 
The error happens when I do
 
shreader=shapefile.Reader(ROUTE.shp)
rsh=shreader.shapes()
 
afterwards.

 
@ Alex : I didn't read instead of editing, it was a typo in my initial
message, sorry but thanks anyway
@ Dave : There is no binary data in my file that I'm aware of, if you
mean in the shapefile, I reckon the library
takes care of it, otherwise it would'nt work at all ?
@ Nate : OK, but I do not understand where to put your correction ?
f.read(8) seems to be required to have a length of 8, due to the format
of the unpack (2i), but even though I tried to replace it with
f.read(8)[:8], it does not work.
 
Sorry again if  I seem kinda slow, I'm really a beginner in python
coding.
 
ST

 Савицкий Александрalexx...@gmail.com 06/02/2012 07:14 


I am having a bit of trouble here with my code, which uses a shapefile
library, named pyshp, to import, edit, and save GIS files within
Python.
So, I open up my shapefile (data is polylines, meaning, not points or
polygons)
shapefile=shapefile.Reader(file.shp)
shps=shapefile.shapes()
shprec = shapefile.records()

Then I carry out some edits, and I save my file.

If you wish to edit your shapefiles, you need to create object: 
shapefile.Editor() or 
shapefile.Write() - if you want create new file.
and then save your edits...
shapefile.Reader object/class for READING shapefile, not for
edit/update


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


Re: [Tutor] Backwards message program

2012-02-07 Thread Steven D'Aprano

myles broomes wrote:

Im trying to code a program where the user enters a message and it is returned 
backwards. Here is my code so far:
 
 
message = input(Enter your message: )
 
backw = 

counter = len(message)
while message != 0:
backw += message[counter-1]
counter -= 1
print(backw)
input(\nPress enter to exit...)


When you want to do something with each item in a sequence, such as each 
character in a string, you can do it directly:


for char in message:
print(char)


prints the characters one at a time.

Python has a built-in command to reverse strings. Actually, two ways: the hard 
way, and the easy way. The hard way is to pull the string apart into 
characters, reverse them, then assemble them back again into a string:



chars = reversed(message)  # Gives the characters of message in reverse order.
new_message = ''.join(chars)


Or written in one line:


new_message = ''.join(reversed(message))


Not very hard at all, is it? And that's the hard way! Here's the easy way: 
using string slicing.


new_message = message[::-1]


I know that's not exactly readable, but slicing is a very powerful tool in 
Python and once you learn it, you'll never go back. Slices take one, two or 
three integer arguments. Experiment with these and see if you can understand 
what slicing does and what the three numbers represent:



message = NOBODY expects the Spanish Inquisition!

message[0]
message[1]

message[39]
message[38]

message[-1]
message[-2]

message[0:6]
message[:6]

message[19:38]
message[19:-1]
message [19:-2]

message[::3]
message[:30:3]
message[5:30:3]


Hint: the two and three argument form of slices is similar to the two and 
three argument form of the range() function.



Python gives you many rich and powerful tools, there's no need to mess about 
with while loops and indexes into a string and nonsense like that if you don't 
need to. As the old saying goes, why bark yourself if you have a dog?




--
Steven

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


Re: [Tutor] decimal precision in python

2012-02-07 Thread Steven D'Aprano

Steve Willoughby wrote:

On 06-Feb-12 07:25, Kapil Shukla wrote:

i tried writing a small code to calculate option price using the
binomial tree model. I compared my results with results of the same
program in excel. There seems to be a minor difference due to decimal
precision as excel is using 15 decimal precision and python (both 2.7
and 3.1) using 11. (at least that's what shown on shell)


If you need lots of precision, you might consider using the decimal 
class.  It'll cost you speed vs. the native floating-point type but 
won't cause you round-off errors.


I'm afraid that's not correct. Decimal is still subject to rounding errors.

 from decimal import Decimal
 x = 1/Decimal(3)  # one third, as close as a Decimal can give
 x + x + x == 1
False


The difference is that the rounding errors you get with Decimal are usually 
different to the ones you get with binary floats. For example:


 y = 0.1  # one tenth, as close as a binary float can give
 y+y + y+y + y+y + y+y + y+y == 1
False

while the same calculation is exact with Decimal.

The reason for the error is the same in both cases: in the first, 1/3 takes an 
infinite number of decimal digits, while in the second, 1/10 takes an infinite 
number of binary digits. So Decimal 1/3 is not *precisely* 1/3, and float 1/10 
is not precisely 1/10 either.


Binary floats can store exactly any fraction which can be written as a sum of 
powers of 1/2, e.g.:


0.40625 = 13/32 = 1/4 + 1/8 + 1/32 so can be stored exactly in a float

Every other number is rounded. The same applies to Decimal: it can store 
exactly any fraction which can be written as a sum of powers of 1/10.


The advantage of Decimal is that anything which can be stored as an exact 
float can also be stored as an exact Decimal, plus some numbers which can't be 
written as exact floats. But there are still plenty of numbers which can't be 
stored exactly as either.




--
Steven

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


Re: [Tutor] decimal precision in python

2012-02-07 Thread Steven D'Aprano

Col,

I think you wrote to me personally by accident, instead of to the Tutor list. 
Nothing you said seems to be private, so I've taken the liberty of answering 
back on the list.


col speed wrote:


Just an idea - I'm not an expert by any means, just a dabbler, but:
many years ago, when I was looking at options(I assume you mean the
same as me as in puts etc.)
they were quoted as fractions.
Some fractions can't be quoted as exact decimals and some decimals as
binary, so fractions *may* be more exact.
I believe there is a fractions module, but it is quite easy to create
your own Rational class.


Starting in Python 2.6, there is a fractions module in the standard library. 
Unlike float and Decimal, it is effectively infinite precision:


 from fractions import Fraction
 z = 1/Fraction(3)
 z + z + z == 1
True


This comes at a cost, of course. Unless you are very careful, you can end up 
with fractions like this:


Fraction(2573485501354569, 18014398509481984)

That is very close to 1/7, and in fact it is the exact fraction equal to the 
binary float closest to 1/7:


 Fraction.from_float(1/7.0)
Fraction(2573485501354569, 18014398509481984)


So Fraction is not a panacea either. Unless you take care, you can easily end 
up using an unlimited amount of memory for an extremely precise number, when a 
much lower precision would be close enough -- or possibly even BETTER:


 Fraction.from_float(1/7.0).limit_denominator(10)
Fraction(1, 7)


But yes, Fractions are a sadly under-appreciated tool for numeric calculations.


--
Steven

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


Re: [Tutor] decimal precision in python

2012-02-07 Thread Steve Willoughby

On 07-Feb-12 03:15, Steven D'Aprano wrote:

Steve Willoughby wrote:

If you need lots of precision, you might consider using the decimal
class. It'll cost you speed vs. the native floating-point type but
won't cause you round-off errors.


I'm afraid that's not correct. Decimal is still subject to rounding errors.

  from decimal import Decimal
  x = 1/Decimal(3) # one third, as close as a Decimal can give
  x + x + x == 1
False


Sorry, I guess I took it for granted that was understood.  I was 
referring to round-off caused by binary representation of a number that 
by all appearances is a simple, rational, non-repeating decimal number 
expressed in base 10.


In other words, when you're adding up financial figures, you'll get an 
accurate sum without mysterious rounding off, but of course certain 
fractions which don't have a straightforward way to represent as a 
decimal value, like 1/3, are going to be an issue.  Good catch, though, 
it was better to point that out.



--
Steve Willoughby / st...@alchemy.com
A ship in harbor is safe, but that is not what ships are built for.
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread Sarma Tangirala
On 7 February 2012 13:49, Alan Gauld alan.ga...@btinternet.com wrote:

 On 07/02/12 01:01, Nate Lastname wrote:

 Exponents ... are **(or ^)


 Not quite the ^ operator is a bitwise XOR...

  2^2
 0
  2^1
 3

 pow() is the other way to do exponents.


Is is better to use pow() against **?


 --
 Alan G
 Author of the Learn to Program web site
 http://www.alan-g.me.uk/

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




-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Backwards message program

2012-02-07 Thread Joel Goldstick
On Tue, Feb 7, 2012 at 5:41 AM, Steven D'Aprano st...@pearwood.info wrote:
 myles broomes wrote:

 Im trying to code a program where the user enters a message and it is
 returned backwards. Here is my code so far:
  message = input(Enter your message: )
  backw = 
 counter = len(message)
 while message != 0:
    backw += message[counter-1]
    counter -= 1
 print(backw)
 input(\nPress enter to exit...)


 When you want to do something with each item in a sequence, such as each
 character in a string, you can do it directly:

 for char in message:
    print(char)


 prints the characters one at a time.

 Python has a built-in command to reverse strings. Actually, two ways: the
 hard way, and the easy way. The hard way is to pull the string apart into
 characters, reverse them, then assemble them back again into a string:


 chars = reversed(message)  # Gives the characters of message in reverse
 order.
 new_message = ''.join(chars)


 Or written in one line:


 new_message = ''.join(reversed(message))


 Not very hard at all, is it? And that's the hard way! Here's the easy way:
 using string slicing.

 new_message = message[::-1]


 I know that's not exactly readable, but slicing is a very powerful tool in
 Python and once you learn it, you'll never go back. Slices take one, two or
 three integer arguments. Experiment with these and see if you can understand
 what slicing does and what the three numbers represent:


 message = NOBODY expects the Spanish Inquisition!

 message[0]
 message[1]

 message[39]
 message[38]

 message[-1]
 message[-2]

 message[0:6]
 message[:6]

 message[19:38]
 message[19:-1]
 message [19:-2]

 message[::3]
 message[:30:3]
 message[5:30:3]


 Hint: the two and three argument form of slices is similar to the two and
 three argument form of the range() function.


 Python gives you many rich and powerful tools, there's no need to mess about
 with while loops and indexes into a string and nonsense like that if you
 don't need to. As the old saying goes, why bark yourself if you have a dog?



 --
 Steven


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

While you should know about reverse, and understand slices, your
program will work if you test for while counter != 0 instead of
message.  Message doesn't change

message = input(Enter your message: )

backw = 
counter = len(message)

#while message != 0: # not this
while counter != 0: # this
backw += message[counter-1]
counter -= 1

print(backw)
input(\nPress enter to exit...)


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


[Tutor] Backspace Escape Sequence; \b

2012-02-07 Thread Garland W. Binns
Could someone please tell me a common or semi-frequent scenario in which a 
person would use a backspace escape sequence? 

Thanks,
Garland

--
Sent via Mobile



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


Re: [Tutor] Backspace Escape Sequence; \b

2012-02-07 Thread Peter Otten
Garland W. Binns wrote:

 Could someone please tell me a common or semi-frequent scenario in which a
 person would use a backspace escape sequence?

Does

$ python -c 'print this is b\bbo\bol\bld\bd' | less

qualify? If you are using (e. g.) Linux this technique is used to show some 
text in boldface when you type something like

 help(str)

in Python's interactive interpreter.


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


Re: [Tutor] Backspace Escape Sequence; \b

2012-02-07 Thread Steven D'Aprano

Peter Otten wrote:

Garland W. Binns wrote:


Could someone please tell me a common or semi-frequent scenario in which a
person would use a backspace escape sequence?


Does

$ python -c 'print this is b\bbo\bol\bld\bd' | less

qualify? If you are using (e. g.) Linux this technique is used to show some 
text in boldface 


Gah, that has got to be the ugliest hack in the universe.

I don't think that is guaranteed to work everywhere. less supports the \b 
trick, but the Python interactive interpreter doesn't support it directly.




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


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread Alan Gauld

On 07/02/12 16:54, Sarma Tangirala wrote:


Is is better to use pow() against **?


I suspect ** will be faster since it doesn't have the function
call overhead.

But I haven't tried timing it. Feel free to do some tests and find out.
Let us know how you get on!


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread Steven D'Aprano

Sarma Tangirala wrote:


Is is better to use pow() against **?



Advantages of **

- it is shorter to type x**y vs pow(x, y)
- being an operator, it is slightly faster than calling a function
- you can't monkey-patch it

Disadvantages of **

- being an operator, you can't directly use it as a function-object
- it can't take three arguments
- hard to google for **
- you can't monkey-patch it

Advantages of pow()

- it is a function, so you can pass it around as an object
- three argument form
- easy to call help(pow) to see documentation
- easy to google for pow
- can be monkey-patched

Disadvantages of pow()

- a tiny bit slower due to the function call
- slightly longer to type
- can be monkey-patched


Weigh up the advantages and disadvantages of each, and make the call which is 
better for you.


(My preference is to use the ** operator.)



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


Re: [Tutor] Backspace Escape Sequence; \b

2012-02-07 Thread Alan Gauld

On 07/02/12 17:19, Garland W. Binns wrote:

Could someone please tell me a common or semi-frequent scenario in which
a person would use a backspace escape sequence?


Do you mean backspace specifically or do you really mean backslash?

In other words are you looking for a use of literal backspaces in a 
string or are you looking at the use of escaped characters in general?


backspace specifically is not commonly used but is sometimes handy for 
positioning the cursor in the middle of a line.

eg

raw_input(Area:acres\b\b\b\b\b\b\b\b)

Should output the prompt line with the cursor positioned in the gap 
between Area: and acres.



 raw_input(Area:acres\b\b\b\b\b\b\b\b)
Area: 45 acres
'45'


But in the general sense there are lots of scenarios where we use 
escaped characters.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


[Tutor] (no subject)

2012-02-07 Thread Debashish Saha
for i in range(1, 8):
print(i)
if i==3:
break
else:
print('The for loop is over')


 Output:
1
2
3

Question:but after breaking the for loop why the else command could not work?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] confusion with else command

2012-02-07 Thread Debashish Saha
for i in range(1, 8):
print(i)
if i==3:
break
else:
print('The for loop is over')


Output:
1
2
3

Question:

but after breaking the for loop why the else loop could not work?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread Sarma Tangirala
On 8 February 2012 00:01, Steven D'Aprano st...@pearwood.info wrote:

 Sarma Tangirala wrote:

  Is is better to use pow() against **?



 Advantages of **

 - it is shorter to type x**y vs pow(x, y)
 - being an operator, it is slightly faster than calling a function
 - you can't monkey-patch it

 Disadvantages of **

 - being an operator, you can't directly use it as a function-object
 - it can't take three arguments
 - hard to google for **
 - you can't monkey-patch it

 Advantages of pow()

 - it is a function, so you can pass it around as an object
 - three argument form
 - easy to call help(pow) to see documentation
 - easy to google for pow
 - can be monkey-patched

 Disadvantages of pow()

 - a tiny bit slower due to the function call
 - slightly longer to type
 - can be monkey-patched


 Weigh up the advantages and disadvantages of each, and make the call which
 is better for you.

 (My preference is to use the ** operator.)


A simple function call argument would have done! :D Thanks for the survey!

Anyway, I was wondering about this, if internally pow() actually uses **. :P




 --
 Steven

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




-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] confusion with else command

2012-02-07 Thread Dave Angel

On 02/07/2012 01:52 PM, Debashish Saha wrote:

for i in range(1, 8):
 print(i)
 if i==3:
 break
else:
 print('The for loop is over')


Output:
1
2
3

Question:

but after breaking the for loop why the else loop could not work?


It works fine.  The else clause of a for loop executes only if the loop 
completes without breaking out.


If the language designers had wanted it to always execute, why have an 
extra keyword?


--

DaveA

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


Re: [Tutor] confusion with else command

2012-02-07 Thread Peter Otten
Debashish Saha wrote:

 for i in range(1, 8):
 print(i)
 if i==3:
 break
 else:
 print('The for loop is over')

 Output:
 1
 2
 3
 
 Question:
 
 but after breaking the for loop why the else loop could not work?

The else suite is not invoked because that's the way Guido intended it ;)
It was designed for sitiuations like the following:

for beast in animals:
if is_it_a_cat(beast):
print(There's a cat among those animals)
break
else:
print(Sorry, there aren't any cats)
print(I've been looking for a cat) # you don't need an else for that

i. e. it's only invoked if the loop terminates normally (no break, and of 
course no return or exception).

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


Re: [Tutor] (no subject)

2012-02-07 Thread Hugo Arts
On Tue, Feb 7, 2012 at 7:50 PM, Debashish Saha silid...@gmail.com wrote:
 for i in range(1, 8):
    print(i)
    if i==3:
        break
 else:
    print('The for loop is over')


  Output:
 1
 2
 3

 Question:but after breaking the for loop why the else command could not work?


because the else statement was designed to be that way:

http://docs.python.org/reference/compound_stmts.html#for

quoting the relevant part:

When the items are exhausted (which is immediately when the sequence
is empty), the suite in the else clause, if present, is executed, and
the loop terminates.

A break statement executed in the first suite terminates the loop
without executing the else clause’s suite.

in short, the else clause only executes if you do *not* break out of the loop.

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


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread Dave Angel

On 02/07/2012 01:57 PM, Sarma Tangirala wrote:

On 8 February 2012 00:01, Steven D'Apranost...@pearwood.info  wrote:


Sarma Tangirala wrote:

  Is is better to use pow() against **?

Advantages of **

- it is shorter to type x**y vs pow(x, y)
- being an operator, it is slightly faster than calling a function
- you can't monkey-patch it

Disadvantages of **

- being an operator, you can't directly use it as a function-object
- it can't take three arguments
- hard to google for **
- you can't monkey-patch it

Advantages of pow()

- it is a function, so you can pass it around as an object
- three argument form
- easy to call help(pow) to see documentation
- easy to google for pow
- can be monkey-patched

Disadvantages of pow()

- a tiny bit slower due to the function call
- slightly longer to type
- can be monkey-patched


Weigh up the advantages and disadvantages of each, and make the call which
is better for you.

(My preference is to use the ** operator.)



A simple function call argument would have done! :D Thanks for the survey!

Anyway, I was wondering about this, if internally pow() actually uses **. :P


I have no idea, but I'd assume so, unless there's a 3rd argument.   At 
that point, the algorithm must change drastically.


--

DaveA

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


[Tutor] For/Else loops

2012-02-07 Thread Jerry Hill
On Tue, Feb 7, 2012 at 1:50 PM, Debashish Saha silid...@gmail.com wrote:
 for i in range(1, 8):
    print(i)
    if i==3:
        break
 else:
    print('The for loop is over')


  Output:
 1
 2
 3

 Question:but after breaking the for loop why the else command could not work?

Because that's the way a for/else statement works.  The else suite is
only run if you do not break out of the loop.  See the docs here:
http://docs.python.org/reference/compound_stmts.html#the-for-statement

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


Re: [Tutor] Backspace Escape Sequence; \b

2012-02-07 Thread Peter Otten
Steven D'Aprano wrote:

 Peter Otten wrote:
 Garland W. Binns wrote:
 
 Could someone please tell me a common or semi-frequent scenario in which
 a person would use a backspace escape sequence?
 
 Does
 
 $ python -c 'print this is b\bbo\bol\bld\bd' | less
 
 qualify? If you are using (e. g.) Linux this technique is used to show
 some text in boldface
 
 Gah, that has got to be the ugliest hack in the universe.
 
 I don't think that is guaranteed to work everywhere. less supports the \b
 trick, but the Python interactive interpreter doesn't support it directly.

Well, the beauty in that hack is that output devices that don't understand 
it usually interpret \b as backspace and thus still produce a readable 
fallback.

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


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread bob gailer

On 2/7/2012 1:57 PM, Sarma Tangirala wrote:


Anyway, I was wondering about this, if internally pow() actually uses 
**. :P



 from dis  import dis
 dis(lambda a,b:a**b)
  1   0 LOAD_FAST0 (a)
  3 LOAD_FAST1 (b)
  6 BINARY_POWER
  7 RETURN_VALUE
 dis(lambda a,b:pow(a,b))
  1   0 LOAD_GLOBAL  0 (pow)
  3 LOAD_FAST0 (a)
  6 LOAD_FAST1 (b)
  9 CALL_FUNCTION2
 12 RETURN_VALUE

Now you know, and you know how to find out!

To delve any deeper you'd have to inspect the c source for pow.
I'd assume it uses the c exponent operator

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] (no subject)

2012-02-07 Thread bob gailer

Do Not Use (no subject) as a subject!

Read the manual before asking questions like this. If you do not 
understand the documentation tell us what you do not understand.



On 2/7/2012 1:50 PM, Debashish Saha wrote:

for i in range(1, 8):
 print(i)
 if i==3:
 break
else:
 print('The for loop is over')


  Output:
1
2
3

Question:but after breaking the for loop why the else command could not work?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor




--
Bob Gailer
919-636-4239
Chapel Hill NC

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


[Tutor] dictionary of methods calling syntax

2012-02-07 Thread Gregory, Matthew
Hi list,

I'm trying to understand how to use a class-level dictionary to act as a switch 
for class methods.  In the contrived example below, I have the statistic name 
as the key and the class method as the value.

class Statistics(object):
STAT = {
'MEAN': get_mean,
'SUM': get_sum,
}
def __init__(self, a, b):
self.a = a
self.b = b
def get_mean(self):
return (self.a + self.b) / 2.0
def get_sum(self):
return (self.a + self.b)
def get_stat(self, stat):
f = self.STAT[stat.upper()]
return f(self)

if __name__ == '__main__':
spam = Statistics(4, 3)
print spam.get_stat('mean')
print spam.get_stat('sum')

When I try to run this, I get:

  NameError: name 'get_mean' is not defined

If I move the STAT dictionary to the bottom of the class, it works fine.  I 
understand why I get an error, i.e. when the dictionary is created get_mean 
hasn't yet been defined, but I'm wondering if there is a better common practice 
for doing this type of lookup.  My web searches didn't come up with anything 
too applicable.

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


Re: [Tutor] Tutor Digest, Vol 96, Issue 26

2012-02-07 Thread Michael Lewis
On Tue, Feb 7, 2012 at 10:57 AM, tutor-requ...@python.org wrote:

 Send Tutor mailing list submissions to
tutor@python.org

 To subscribe or unsubscribe via the World Wide Web, visit
http://mail.python.org/mailman/listinfo/tutor
 or, via email, send a message with subject or body 'help' to
tutor-requ...@python.org

 You can reach the person managing the list at
tutor-ow...@python.org

 When replying, please edit your Subject line so it is more specific
 than Re: Contents of Tutor digest...


 Today's Topics:

   1. Re: Backspace Escape Sequence; \b (Peter Otten)
   2. Re: Backspace Escape Sequence; \b (Steven D'Aprano)
   3. Re: Question on how to do exponents (Alan Gauld)
   4. Re: Question on how to do exponents (Steven D'Aprano)
   5. Re: Backspace Escape Sequence; \b (Alan Gauld)
   6. (no subject) (Debashish Saha)
   7. confusion with else command (Debashish Saha)
   8. Re: Question on how to do exponents (Sarma Tangirala)


 --

 Message: 1
 Date: Tue, 07 Feb 2012 18:41:12 +0100
 From: Peter Otten __pete...@web.de
 To: tutor@python.org
 Subject: Re: [Tutor] Backspace Escape Sequence; \b
 Message-ID: jgrnmj$g41$1...@dough.gmane.org
 Content-Type: text/plain; charset=ISO-8859-1

 Garland W. Binns wrote:

  Could someone please tell me a common or semi-frequent scenario in which
 a
  person would use a backspace escape sequence?

 Does

 $ python -c 'print this is b\bbo\bol\bld\bd' | less

 qualify? If you are using (e. g.) Linux this technique is used to show some
 text in boldface when you type something like

  help(str)

 in Python's interactive interpreter.




 --

 Message: 2
 Date: Wed, 08 Feb 2012 05:18:35 +1100
 From: Steven D'Aprano st...@pearwood.info
 To: tutor@python.org
 Subject: Re: [Tutor] Backspace Escape Sequence; \b
 Message-ID: 4f316afb.7040...@pearwood.info
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed

 Peter Otten wrote:
  Garland W. Binns wrote:
 
  Could someone please tell me a common or semi-frequent scenario in
 which a
  person would use a backspace escape sequence?
 
  Does
 
  $ python -c 'print this is b\bbo\bol\bld\bd' | less
 
  qualify? If you are using (e. g.) Linux this technique is used to show
 some
  text in boldface

 Gah, that has got to be the ugliest hack in the universe.

 I don't think that is guaranteed to work everywhere. less supports the \b
 trick, but the Python interactive interpreter doesn't support it directly.



 --
 Steven


 --

 Message: 3
 Date: Tue, 07 Feb 2012 18:29:49 +
 From: Alan Gauld alan.ga...@btinternet.com
 To: tutor@python.org
 Subject: Re: [Tutor] Question on how to do exponents
 Message-ID: jgrqit$80s$1...@dough.gmane.org
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed

 On 07/02/12 16:54, Sarma Tangirala wrote:

  Is is better to use pow() against **?

 I suspect ** will be faster since it doesn't have the function
 call overhead.

 But I haven't tried timing it. Feel free to do some tests and find out.
 Let us know how you get on!


 --
 Alan G
 Author of the Learn to Program web site
 http://www.alan-g.me.uk/



 --

 Message: 4
 Date: Wed, 08 Feb 2012 05:31:07 +1100
 From: Steven D'Aprano st...@pearwood.info
 To: tutor@python.org
 Subject: Re: [Tutor] Question on how to do exponents
 Message-ID: 4f316deb.3070...@pearwood.info
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed

 Sarma Tangirala wrote:

  Is is better to use pow() against **?


 Advantages of **

 - it is shorter to type x**y vs pow(x, y)
 - being an operator, it is slightly faster than calling a function
 - you can't monkey-patch it

 Disadvantages of **

 - being an operator, you can't directly use it as a function-object
 - it can't take three arguments
 - hard to google for **
 - you can't monkey-patch it

 Advantages of pow()

 - it is a function, so you can pass it around as an object
 - three argument form
 - easy to call help(pow) to see documentation
 - easy to google for pow
 - can be monkey-patched

 Disadvantages of pow()

 - a tiny bit slower due to the function call
 - slightly longer to type
 - can be monkey-patched


 Weigh up the advantages and disadvantages of each, and make the call which
 is
 better for you.

 (My preference is to use the ** operator.)



 --
 Steven


 --

 Message: 5
 Date: Tue, 07 Feb 2012 18:42:09 +
 From: Alan Gauld alan.ga...@btinternet.com
 To: tutor@python.org
 Subject: Re: [Tutor] Backspace Escape Sequence; \b
 Message-ID: jgrra2$ec8$1...@dough.gmane.org
 Content-Type: text/plain; charset=UTF-8; format=flowed

 On 07/02/12 17:19, Garland W. Binns wrote:
  Could someone please tell me a common or semi-frequent scenario in which
  a person would use a backspace escape sequence?

 Do you mean backspace specifically or do you really mean backslash?

 In other words 

Re: [Tutor] dictionary of methods calling syntax

2012-02-07 Thread Joel Goldstick
On Tue, Feb 7, 2012 at 2:32 PM, Gregory, Matthew
matt.greg...@oregonstate.edu wrote:
 Hi list,

 I'm trying to understand how to use a class-level dictionary to act as a 
 switch for class methods.  In the contrived example below, I have the 
 statistic name as the key and the class method as the value.

 class Statistics(object):
    STAT = {
        'MEAN': get_mean,
        'SUM': get_sum,
    }
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def get_mean(self):
        return (self.a + self.b) / 2.0
    def get_sum(self):
        return (self.a + self.b)
    def get_stat(self, stat):
        f = self.STAT[stat.upper()]
        return f(self)

 if __name__ == '__main__':
    spam = Statistics(4, 3)
    print spam.get_stat('mean')
    print spam.get_stat('sum')

 When I try to run this, I get:

  NameError: name 'get_mean' is not defined

 If I move the STAT dictionary to the bottom of the class, it works fine.  I 
 understand why I get an error, i.e. when the dictionary is created get_mean 
 hasn't yet been defined, but I'm wondering if there is a better common 
 practice for doing this type of lookup.  My web searches didn't come up with 
 anything too applicable.

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

You might want to read through this:
http://stackoverflow.com/questions/5213166/python-forward-declaration-of-functions-inside-classes

Specifically from an answer:
First, in class B, the function foo() is called before being
declared. A does not have this problem because foo() is only called
when the class is instantiated--after the function foo is defined.

So, I think you could move your STAT dictionary definition into the
__init__ method so that is doesn't actually run until you create an
instance of your class.  That being said, I'm not sure that is more
'pythonic' than moving it to the bottom of the class definition

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


Re: [Tutor] dictionary of methods calling syntax

2012-02-07 Thread Alan Gauld

On 07/02/12 19:32, Gregory, Matthew wrote:


class Statistics(object):
 STAT = {
 'MEAN': get_mean,
 'SUM': get_sum,
 }

...


if __name__ == '__main__':
 spam = Statistics(4, 3)
 print spam.get_stat('mean')
 print spam.get_stat('sum')



Since a class is effectively a disguised dictionary I'm not sure why you 
want to do this? If you just want to access the method by name then why 
not just call getattr(spam,'get_mean')?


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Re: [Tutor] Tutor Digest, Vol 96, Issue 26

2012-02-07 Thread Alan Gauld

On 07/02/12 19:45, Michael Lewis wrote:

As the instructions in the message you posted say...


When replying, please edit your Subject line so it is more specific
than Re: Contents of Tutor digest...


And also please delete all the irrelevant stuff, it's almost impossible 
to spot the new material amongst all the other messages. Also it is 
inconsiderate to those who pay for their mail by the byte.


--
Alan G
Moderator.

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


[Tutor] Character Buffer Object Error

2012-02-07 Thread Michael Lewis
I want to find all digits in a string and then increment those digits by 1
and then return the same string with the incremented digits.

I've tried the following code, but I am getting the following error. How do
I do this properly?

def AlterInput(user_input):
print user_input
new_output = ''
for index, char in enumerate(user_input):
if char.isdigit():
new_char = int(char)
new_char += 1
new_output = ' '.join(user_input)
new_output.replace(char, new_char)
print new_output

def GetUserInput():
'''Get a string from the user and pass it'''
user_input = '''I got 432 when I counted, but Jim got 433 which
is a lot for only 6 cats, or were there 12 cats?'''
AlterInput(user_input.split())


Traceback (most recent call last):
  File C:/Python27/Homework/Homework 4_1.py, line 25, in module
GetUserInput()
  File C:/Python27/Homework/Homework 4_1.py, line 23, in GetUserInput
AlterInput(user_input.split())
  File C:/Python27/Homework/Homework 4_1.py, line 15, in AlterInput
new_output.replace(char, new_char)
TypeError: expected a character buffer object

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


Re: [Tutor] Character Buffer Object Error

2012-02-07 Thread Christian Witts

On 2012/02/08 07:56 AM, Michael Lewis wrote:
I want to find all digits in a string and then increment those digits 
by 1 and then return the same string with the incremented digits.


I've tried the following code, but I am getting the following error. 
How do I do this properly?


def AlterInput(user_input):
print user_input
new_output = ''
for index, char in enumerate(user_input):
if char.isdigit():
new_char = int(char)
new_char += 1
new_output = ' '.join(user_input)
new_output.replace(char, new_char)
print new_output

def GetUserInput():
'''Get a string from the user and pass it'''
user_input = '''I got 432 when I counted, but Jim got 433 which
is a lot for only 6 cats, or were there 12 cats?'''
AlterInput(user_input.split())


Traceback (most recent call last):
  File C:/Python27/Homework/Homework 4_1.py, line 25, in module
GetUserInput()
  File C:/Python27/Homework/Homework 4_1.py, line 23, in GetUserInput
AlterInput(user_input.split())
  File C:/Python27/Homework/Homework 4_1.py, line 15, in AlterInput
new_output.replace(char, new_char)
TypeError: expected a character buffer object

Thanks.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
new_char is of type int and not type str, so cast it back to a string 
before using it in your call to .replace as it expects both arguments to 
be strings.

--

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


Re: [Tutor] Character Buffer Object Error

2012-02-07 Thread Asokan Pichai
Dear Michael

Overall I see  a few problems.

0. Functions should return values. Not print them

1. Why use enumerate? The code is not using the index anyway

2. The following line appears wrong.
 new_output = ' '.join(user_input)

3. This line has a very buggy possibility.
 new_output.replace(char, new_char)
Let us say you have 234. First time you will replace 2 with 3, getting 334.
And then you will replace the first 3 with 4 getting 434 and finally
end up with 534. Of course due to other coding errors this does not
come to pass. But your basic idea of using str.replace() is prone
to this problem.

4. How are you supposed to treat 9?

Anyway back to your problem:

 I want to find all digits in a string and then increment those digits by 1
 and then return the same string with the incremented digits.

Pseudocode
--
Initialise and outstring (empty)
Read the instring character by character
if the current character is not a digit
append it to outstring
else
append the transform(current char) to outstring

If you can organize your code like this it may be easier

HTH
Regards

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