Re: Version numbers in Standard Library

2019-03-03 Thread Thomas Jollans
On 01/03/2019 16:35, Thompson, Matt (GSFC-610.1)[SCIENCE SYSTEMS AND
APPLICATIONS INC] via Python-list wrote:
> Dear Python List,
> 
> A question. I help maintain a Python stack for users in my division here
> at NASA and one user asked about updating the re module to 2.4. I
> believe because he read the docs:
> 
> https://docs.python.org/2.7/library/re.html
> 
> where you see lines like "New in version 2.4" and he also did:
> 
> $ python2 -c 'import re; print (re.__version__)'
> 2.2.1
> 
> And, well, one can think "oh, a newer version is needed". I searched on
> conda, etc. and can't find it and finally realized that 2.4 meant Python
> 2.4, not re 2.4. (The 3.7 docs have lines like "Changed in version 3.7".)
> 
> My question to the pros here is what purpose do the __version__/version
> variables serve in the Python Standard Library?  I can understand in
> external packages, but once in the Standard Library...?
If a module that started life outside the standard library is included
in the standard library under the same name, it is taken aboard hook,
line and sinker. If it has a __version__, then that should probably
stay: code that used the module before it entered the standard library
might rely on it.

As you quite rightly point out, these lines are then completely
pointless, so there's no reason to ever change them.

> 
> For example, in re.py, that line was last changed 18 years ago according
> to git blame. In tarfile.py, the version string was last changed 12
> years ago. But in both, the modules were edited in 2018 so they haven't
> been static for a decade.
> 
> Are those strings there just for historic purposes?
> 
> Not a big deal, I was just wondering.
> 
> Thanks,
> Matt
> 

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


Re: Version numbers in Standard Library

2019-03-01 Thread Skip Montanaro
The point of the "Changed in version ..." or "New in version ..." bits
in the documentation is to alert readers who maintain software which
needs to remain backward compatible with older versions of Python. If
you maintain a package which you support for Python 3.4, 3.5, 3.6, and
3.7, you'll probably shy away from bits which weren't around for 3.4,
and be careful about APIs which have changed since 3.4.

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: converting numbers into words

2017-11-09 Thread Grant Edwards
On 2017-11-09, r161...@rguktrkv.ac.in  wrote:

> How can I covert numbers into word like ex:-123 One hundred twenty three?

That's one of the classic freshman intro-to-programming homework
problems.  I remember having to write a Pascal program to do that back
in the 70's...

-- 
Grant Edwards   grant.b.edwardsYow! Are we laid back yet?
  at   
  gmail.com

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


Re: converting numbers into words (Posting On Python-List Prohibited)

2017-11-09 Thread Christopher Reimer
On Nov 9, 2017, at 3:45 AM, John Ladasky  wrote:
> 
>> On Wednesday, November 8, 2017 at 11:40:18 PM UTC-8, Lawrence D’Oliveiro 
>> wrote:
>>> On Thursday, November 9, 2017 at 7:51:35 PM UTC+13, r16...@rguktrkv.ac.in 
>>> wrote:
>>> 
>>> How can I covert numbers into word like ex:-123 One hundred twenty three?
>> 
>> Here’s  one I 
>> did earlier, in Algol 68.
>> 
>> Conversion to Python is left as an exercise for the reader.
> 
> I think that gives away rather more than I wanted the student to see.
> -- 
> https://mail.python.org/mailman/listinfo/python-list

I thought the classic homework problem was to convert an Arabic numeral into a 
Roman numeral. Bonus points for correctly converting any number above 12 and/or 
copyright year from any old movie. Most students have seen Roman numerals on 
clocks (1-12).

Maybe that's too hard for today's kids with digital clocks.

Chris R.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: converting numbers into words

2017-11-09 Thread bartc

On 09/11/2017 06:51, r161...@rguktrkv.ac.in wrote:

How can I covert numbers into word like ex:-123 One hundred twenty three?



google for something like "algorithm numbers to words".

If this is homework, then it's not cheating as everyone else will be 
doing the same.


> How can I covert numbers into word like ex:-123 One hundred twenty three?

And you need to refine your specification of the task. I would render 
your example as:


 minus one hundred and twenty-three




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


Re: converting numbers into words (Posting On Python-List Prohibited)

2017-11-09 Thread John Ladasky
On Wednesday, November 8, 2017 at 11:40:18 PM UTC-8, Lawrence D’Oliveiro wrote:
> On Thursday, November 9, 2017 at 7:51:35 PM UTC+13, r16...@rguktrkv.ac.in 
> wrote:
> 
> > How can I covert numbers into word like ex:-123 One hundred twenty three?
> 
> Here’s  one I 
> did earlier, in Algol 68.
> 
> Conversion to Python is left as an exercise for the reader.

I think that gives away rather more than I wanted the student to see.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: converting numbers into words

2017-11-08 Thread jladasky
On Wednesday, November 8, 2017 at 10:51:35 PM UTC-8, r16...@rguktrkv.ac.in 
wrote:
> How can I covert numbers into word like ex:-123 One hundred twenty three?

That's a classic homework exercise.  Expect guidance, not an answer.

Why don't you solve a related, but simpler task first?  This is a good approach 
to learning computer programming.  Write a program that accepts a single digit 
as input, and outputs the corresponding word.  Post the code here.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Format numbers

2015-11-15 Thread MRAB

On 2015-11-15 17:30, Seymore4Head wrote:

Just screwing around making up practice problems.  I can't get the
format right.  I am trying to learn how to get a output line to line
up neatly.

import random
lo=1
hi=1 # I am adding or subtracting 0s from this input number
fm=len(str(hi)) # This counts the digits of the input number
print fm
a=random.randrange(lo,hi+1)
count=0
guess=0

while guess != a:
 guess=random.randrange(lo,hi + 1)
 print "guess =",

 print "{:8d}".format(guess),  #what I would like to do is use
the variable fm instead of the number 8 here so the number of fields
are the same as the input number.

 count+=1
 if guess==a:
 print " The hidden number was",a
 print
 print "You guessed right in ",
 if guess >a:
 print " Guess Lower"
 hi=guess
 if guess < a:
 lo=guess
 print " Guess Higher"
print count
print " turns"


The part of the format placeholder that specifies the width can also be
placeholder, like this:

print "{:{}d}".format(guess, fm)

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


Re: Format numbers

2015-11-15 Thread Seymore4Head
On Sun, 15 Nov 2015 19:00:42 +, MRAB 
wrote:

>On 2015-11-15 17:30, Seymore4Head wrote:
>> Just screwing around making up practice problems.  I can't get the
>> format right.  I am trying to learn how to get a output line to line
>> up neatly.
>>
>> import random
>> lo=1
>> hi=1 # I am adding or subtracting 0s from this input number
>> fm=len(str(hi)) # This counts the digits of the input number
>> print fm
>> a=random.randrange(lo,hi+1)
>> count=0
>> guess=0
>>
>> while guess != a:
>>  guess=random.randrange(lo,hi + 1)
>>  print "guess =",
>>
>>  print "{:8d}".format(guess),  #what I would like to do is use
>> the variable fm instead of the number 8 here so the number of fields
>> are the same as the input number.
>>
>>  count+=1
>>  if guess==a:
>>  print " The hidden number was",a
>>  print
>>  print "You guessed right in ",
>>  if guess >a:
>>  print " Guess Lower"
>>  hi=guess
>>  if guess < a:
>>  lo=guess
>>  print " Guess Higher"
>> print count
>> print " turns"
>>
>The part of the format placeholder that specifies the width can also be
>placeholder, like this:
>
> print "{:{}d}".format(guess, fm)

That works
Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lucky numbers in Python

2015-04-30 Thread Cecil Westerhof
Op Thursday 30 Apr 2015 04:55 CEST schreef Ian Kelly:

 On Wed, Apr 29, 2015 at 6:01 PM, Cecil Westerhof ce...@decebal.nl wrote:
 Op Thursday 30 Apr 2015 00:38 CEST schreef Ian Kelly:
 In that case you can definitely omit the middle term of the slice,
 which will be both more concise and clearer in intent, though
 probably not significantly faster.

 It is certainly nit faster. It is even significantly slower. With
 the middle term lucky_numbers(int(1e6)) takes 0.13 seconds. Without
 it takes 14.3 seconds. Hundred times as long.

 That would be rather surprising, since it's the same operation being
 performed, so I did my own timing and came up with 0.25 seconds
 (best of 3) with the middle term and 0.22 seconds without.

 I suspect that you tested it as del sieve[skip_count - 1 :
 skip_count] (which would delete only one item) rather than del
 sieve[skip_count - 1 :: skip_count].

Yeah, that is how I interpreted omitting the middle term. But it
seemed to give the right results.

With your amendment it runs slightly faster. With 1E7 it is 8.0 and
7.7. So almost 4% faster.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lucky numbers in Python

2015-04-30 Thread Cecil Westerhof
Because I want the code to work with Python 3 also, the code is now:
def lucky_numbers(n):

Lucky numbers from 1 up-to n
http://en.wikipedia.org/wiki/Lucky_number


if n  3:
return [1]
sieve = list(range(1, n + 1, 2))
sieve_index = 1
while True:
sieve_len   = len(sieve)
if (sieve_index + 1)  sieve_len:
break
skip_count  = sieve[sieve_index]
if sieve_len  skip_count:
break
del sieve[skip_count - 1 : : skip_count]
sieve_index += 1
return sieve

It looks like the list in:
sieve = list(range(1, n + 1, 2))

does not have much influence in Python 2. So I was thinking of leaving
the code like it is. Or is it better to check and do the list only
with Python 3?

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lucky numbers in Python

2015-04-30 Thread Dave Angel

On 04/30/2015 02:55 PM, Cecil Westerhof wrote:

Because I want the code to work with Python 3 also, the code is now:
 def lucky_numbers(n):
 
 Lucky numbers from 1 up-to n
 http://en.wikipedia.org/wiki/Lucky_number
 

 if n  3:
 return [1]
 sieve = list(range(1, n + 1, 2))
 sieve_index = 1
 while True:
 sieve_len   = len(sieve)
 if (sieve_index + 1)  sieve_len:
 break
 skip_count  = sieve[sieve_index]
 if sieve_len  skip_count:
 break
 del sieve[skip_count - 1 : : skip_count]
 sieve_index += 1
 return sieve

It looks like the list in:
 sieve = list(range(1, n + 1, 2))

does not have much influence in Python 2. So I was thinking of leaving
the code like it is. Or is it better to check and do the list only
with Python 3?



I'd do something like this at top of the module:

try:
range = xrange
except NameError as ex:
pass

then use range as it is defined in Python3.

if that makes you nervous, then define irange = xrange, and if it gets a 
NameError exception, irange = range



--
DaveA
--
https://mail.python.org/mailman/listinfo/python-list


Re: Lucky numbers in Python

2015-04-29 Thread Ian Kelly
On Wed, Apr 29, 2015 at 12:24 PM, Cecil Westerhof ce...@decebal.nl wrote:
 I was wondering if there is a way to do this:
 for del_index in range((sieve_len // skip_count) * skip_count - 1,
   skip_count - 2, -skip_count):
 del sieve[del_index]
 in a more efficient way.

You can delete using slices.

del sieve[(sieve_len // skip_count) * skip_count - 1 : skip_count - 2
: -skip_count]

Now you no longer need to do the iteration in reverse, which makes the
slicing simpler:

del sieve[skip_count - 1 : (sieve_len // skip_count) * skip_count : skip_count]

And although it's not clear to me what this is supposed to be doing,
you probably no longer need the middle term if the intention is to
continue deleting all the way to the end of the list (if it is then I
think you have a bug in the existing implementation, since the last
item in the list can never be deleted).

del sieve[skip_count - 1 :: skip_count]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lucky numbers in Python

2015-04-29 Thread Cecil Westerhof
Op Wednesday 29 Apr 2015 21:57 CEST schreef Ian Kelly:

 On Wed, Apr 29, 2015 at 12:24 PM, Cecil Westerhof ce...@decebal.nl wrote:
 I was wondering if there is a way to do this:
 for del_index in range((sieve_len // skip_count) * skip_count - 1,
 skip_count - 2, -skip_count):
 del sieve[del_index]
 in a more efficient way.

 You can delete using slices.

 del sieve[(sieve_len // skip_count) * skip_count - 1 : skip_count -
 2 : -skip_count]

 Now you no longer need to do the iteration in reverse, which makes
 the slicing simpler:

 del sieve[skip_count - 1 : (sieve_len // skip_count) * skip_count :
 skip_count]

I expected that it could be done more efficiently, but did not expect
such a big difference: more as hundred times. The old situation took
20 seconds for 100. The new takes 0.17.

The code is know (I added a missing check):
def lucky_numbers(n):
if n  3:
return [1]
sieve = range(1, n + 1, 2)
sieve_index = 1
while True:
sieve_len   = len(sieve)
if (sieve_index + 1)  sieve_len:
break
skip_count  = sieve[sieve_index]
if sieve_len  skip_count:
break
del sieve[skip_count - 1 : (sieve_len // skip_count) * skip_count : 
skip_count]
sieve_index += 1
return sieve


 And although it's not clear to me what this is supposed to be doing,
 you probably no longer need the middle term if the intention is to
 continue deleting all the way to the end of the list (if it is then
 I think you have a bug in the existing implementation, since the
 last item in the list can never be deleted).

What do you mean by this? Executing:
lucky_numbers(5)
gives:
[1, 3]

So the last element (5) is deleted.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lucky numbers in Python

2015-04-29 Thread Ian Kelly
On Wed, Apr 29, 2015 at 3:45 PM, Cecil Westerhof ce...@decebal.nl wrote:
 Op Wednesday 29 Apr 2015 21:57 CEST schreef Ian Kelly:
 And although it's not clear to me what this is supposed to be doing,
 you probably no longer need the middle term if the intention is to
 continue deleting all the way to the end of the list (if it is then
 I think you have a bug in the existing implementation, since the
 last item in the list can never be deleted).

 What do you mean by this? Executing:
 lucky_numbers(5)
 gives:
 [1, 3]

 So the last element (5) is deleted.

Off by one error on my part. This is why negative skip values on
ranges and slices are not recommended: they're confusing. :-)

In that case you can definitely omit the middle term of the slice,
which will be both more concise and clearer in intent, though probably
not significantly faster.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lucky numbers in Python

2015-04-29 Thread Chris Kaynor
On Wed, Apr 29, 2015 at 2:45 PM, Cecil Westerhof ce...@decebal.nl wrote:

  I was wondering if there is a way to do this:
  for del_index in range((sieve_len // skip_count) * skip_count - 1,
  skip_count - 2, -skip_count):
  del sieve[del_index]
  in a more efficient way.
 
  You can delete using slices.
 
  del sieve[(sieve_len // skip_count) * skip_count - 1 : skip_count -
  2 : -skip_count]
 
  Now you no longer need to do the iteration in reverse, which makes
  the slicing simpler:
 
  del sieve[skip_count - 1 : (sieve_len // skip_count) * skip_count :
  skip_count]

 I expected that it could be done more efficiently, but did not expect
 such a big difference: more as hundred times. The old situation took
 20 seconds for 100. The new takes 0.17.


Its not too surprising, as deleting the non-end element of a list is a O(n)
operation - it must copy all elements in the list into a new list each
time. This means that your algorithm is roughly O(n*n*log(n)) performance -
n for each list delete, which is wrapped in a for loop of n iterations,
which is wrapped in a while loop which will run log(n) times (I think that
while loop will run log(n) times, but have not actually tested the math).

Deleting a slice should take n time as well, however it is now done only
once rather than once per item to be removed, which should reduce the
overall algorithm to O(n*log(n)) time - aka, a HUGE difference with any
moderate to large input.

Chris
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lucky numbers in Python

2015-04-29 Thread Steven D'Aprano
On Thu, 30 Apr 2015 05:57 am, Ian Kelly wrote:

 On Wed, Apr 29, 2015 at 12:24 PM, Cecil Westerhof ce...@decebal.nl
 wrote:
 I was wondering if there is a way to do this:
 for del_index in range((sieve_len // skip_count) * skip_count
 - 1,
   skip_count - 2, -skip_count):
 del sieve[del_index]
 in a more efficient way.
 
 You can delete using slices.
 
 del sieve[(sieve_len // skip_count) * skip_count - 1 : skip_count - 2
 : -skip_count]
 
 Now you no longer need to do the iteration in reverse, which makes the
 slicing simpler:
 
 del sieve[skip_count - 1 : (sieve_len // skip_count) * skip_count :
 skip_count]

True, but *probably* at the expense of speed. When you delete items from a
list, the remaining items have to be moved, which takes time, especially
for very large lists.

Most of the time, rather than deleting items, it is faster to set them to a
placeholder (for example None) and then copy the ones which aren't None in
a separate loop:


def erat(n):
Return a list of primes up to and including n.

This is a fixed-size version of the Sieve of Eratosthenes, using an
adaptation of the traditional algorithm.

 erat(30)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]


if n  2:
return []
# Generate a fixed array of integers.
arr = list(range(n+1))  # A list is faster than an array.
# Cross out 0 and 1 since they aren't prime.
arr[0] = arr[1] = None
i = 2
while i*i = n:
# Cross out all the multiples of i starting from i**2.
for p in range(i*i, n+1, i):
arr[p] = None
# Advance to the next number not crossed off.
i += 1
while i = n and arr[i] is None:
i += 1
# Copy the items which aren't None.
return list(filter(None, arr))


The above is written for Python 3. In Python 2, you can safely drop the two
calls to list() since both range and filter already return lists.

Another alternative is to use slice assignment of the slices that you don't
delete, rather than deleting directly:


del alist[5:55]

is similar to:

alist[:] = alist[:4] + alist[55:]  # Note the [:] on the left.


Which is faster will probably depend on the specifics of the list.

But of course for small lists, none of this matters and you should just use
whatever is easiest and most natural to read.




-- 
Steven

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


Re: Lucky numbers in Python

2015-04-29 Thread Cecil Westerhof
Op Thursday 30 Apr 2015 00:38 CEST schreef Ian Kelly:

 On Wed, Apr 29, 2015 at 3:45 PM, Cecil Westerhof ce...@decebal.nl wrote:
 Op Wednesday 29 Apr 2015 21:57 CEST schreef Ian Kelly:
 And although it's not clear to me what this is supposed to be
 doing, you probably no longer need the middle term if the
 intention is to continue deleting all the way to the end of the
 list (if it is then I think you have a bug in the existing
 implementation, since the last item in the list can never be
 deleted).

 What do you mean by this? Executing:
 lucky_numbers(5)
 gives:
 [1, 3]

 So the last element (5) is deleted.

 Off by one error on my part. This is why negative skip values on
 ranges and slices are not recommended: they're confusing. :-)

 In that case you can definitely omit the middle term of the slice,
 which will be both more concise and clearer in intent, though
 probably not significantly faster.

It is certainly nit faster. It is even significantly slower. With the
middle term lucky_numbers(int(1e6)) takes 0.13 seconds. Without it
takes 14.3 seconds. Hundred times as long.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lucky numbers in Python

2015-04-29 Thread Ian Kelly
On Wed, Apr 29, 2015 at 6:01 PM, Cecil Westerhof ce...@decebal.nl wrote:
 Op Thursday 30 Apr 2015 00:38 CEST schreef Ian Kelly:
 In that case you can definitely omit the middle term of the slice,
 which will be both more concise and clearer in intent, though
 probably not significantly faster.

 It is certainly nit faster. It is even significantly slower. With the
 middle term lucky_numbers(int(1e6)) takes 0.13 seconds. Without it
 takes 14.3 seconds. Hundred times as long.

That would be rather surprising, since it's the same operation being
performed, so I did my own timing and came up with 0.25 seconds (best
of 3) with the middle term and 0.22 seconds without.

I suspect that you tested it as del sieve[skip_count - 1 :
skip_count] (which would delete only one item) rather than del
sieve[skip_count - 1 :: skip_count].
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Lucky numbers in Python

2015-04-29 Thread Ian Kelly
On Wed, Apr 29, 2015 at 6:11 PM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Thu, 30 Apr 2015 05:57 am, Ian Kelly wrote:

 On Wed, Apr 29, 2015 at 12:24 PM, Cecil Westerhof ce...@decebal.nl
 wrote:
 I was wondering if there is a way to do this:
 for del_index in range((sieve_len // skip_count) * skip_count
 - 1,
   skip_count - 2, -skip_count):
 del sieve[del_index]
 in a more efficient way.

 You can delete using slices.

 del sieve[(sieve_len // skip_count) * skip_count - 1 : skip_count - 2
 : -skip_count]

 Now you no longer need to do the iteration in reverse, which makes the
 slicing simpler:

 del sieve[skip_count - 1 : (sieve_len // skip_count) * skip_count :
 skip_count]

 True, but *probably* at the expense of speed. When you delete items from a
 list, the remaining items have to be moved, which takes time, especially
 for very large lists.

 Most of the time, rather than deleting items, it is faster to set them to a
 placeholder (for example None) and then copy the ones which aren't None in
 a separate loop:

You're correct, but I think this would be difficult to apply to the
OP's algorithm since the list indexing depends on the items from
previous iterations having been removed.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Joel Goldstick
On Sun, Jan 11, 2015 at 2:31 PM, Store Makhzan stor...@gmail.com wrote:
 I have this script which can calculate the total of numbers given in a string
  script -
 total = 0
 for c in '0123456789':
total += int(c)
 print total
  script -

 How should I modify this script to find the total of if the numbers given in 
 the string form have decimal places? That is, how do I need to modify this 
 line:
 - script -
 for c in '1.32, 5.32, 4.4, 3.78':
 - script -
 to find the total of these given numbers.
 --
 https://mail.python.org/mailman/listinfo/python-list

split the string on ',' to get a list of strings.  loop thru list
using float(s), add float values


-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Store Makhzan
On Sunday, January 11, 2015 at 2:06:54 PM UTC-6, Joel Goldstick wrote:
 On Sun, Jan 11, 2015 at 2:31 PM, Store Makhzan wrote:
  I have this script which can calculate the total of numbers given in a 
  string
   script -
  total = 0
  for c in '0123456789':
 total += int(c)
  print total
   script -
 
  How should I modify this script to find the total of if the numbers given 
  in the string form have decimal places? That is, how do I need to modify 
  this line:
  - script -
  for c in '1.32, 5.32, 4.4, 3.78':
  - script -
  to find the total of these given numbers.
  --
  https://mail.python.org/mailman/listinfo/python-list
 
 split the string on ',' to get a list of strings.  loop thru list
 using float(s), add float values
 
 
 -- 
 Joel Goldstick
 http://joelgoldstick.com

Thank you
Here is what I did:

- script -
#Check if a perfect cube
total = 0
for c in ('1.23', '2.4', '3.123'):
   print float(c)
   total += float(c)
print total
- script -

Which gave me the result I wanted.
Since I am new to Python, I used () as a guess, and it worked.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Joel Goldstick
On Sun, Jan 11, 2015 at 6:12 PM, Thomas 'PointedEars' Lahn
pointede...@web.de wrote:
 Joel Goldstick wrote:

 Thomas 'PointedEars' Lahn wrote:
 Joel Goldstick wrote:
 my_list = 1.23, 2.4, 3.123.split(,)

 that will give you ['1.23', '2.4', '3.123']

 No, it gives

 […]
 |  my_list = 1.23, 2.4, 3.123.split(,)
 |  my_list
 | ['1.23', ' 2.4', ' 3.123']
^   ^
 | 

 In order to get the result you described, one needs at least

 |  '1.23, 2.4, 3.123'.split(', ')
 | ['1.23', '2.4', '3.123']

 […]

 I'm not sure what you are trying to point out as your examples confirm
 my code.

 No, they don't.

 Am I missing something.
 ^
 (Is that a question.)

 You are missing a leading space character because in the string the comma
 was followed by one.

I see that now.  Performing float on each element of the list will
take care of that, or I guess .strip() on each first.

 As for feeding a beginner regex solutions, I'm on the side that this
 is a terrible idea.  Regex is not something a beginner should worry
 about!

 NAK.

 --
 PointedEars

 Twitter: @PointedEars2
 Please do not cc me. / Bitte keine Kopien per E-Mail.
 --
 https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Thomas 'PointedEars' Lahn
Joel Goldstick wrote:

 On Sun, Jan 11, 2015 at 6:12 PM, Thomas 'PointedEars' Lahn
 pointede...@web.de wrote:
 Joel Goldstick wrote:
 Am I missing something.
^
 […]
 You are missing a leading space character because in the string the comma
 was followed by one.
 
 I see that now.  Performing float on each element of the list will
 take care of that, or I guess .strip() on each first.

As I showed, .strip() is unnecessary.  But float() is always necessary for 
computing the sum and suffices indeed together with s.split() if s is just a 
comma-separated list of numeric strings with optional whitespace leading and 
trailing the comma:

  print(sum(map(lambda x: float(x), s.split(',')))

Please trim your quotes to the relevant minimum.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Mark Lawrence

On 11/01/2015 23:07, Thomas 'PointedEars' Lahn wrote:

Store Makhzan wrote:


I have this script which can calculate the total of numbers given in a
string […]
total = 0
for c in '0123456789':
total += int(c)
print total

[…]
How should I modify this script to find the total of if the numbers given
in the string form have decimal places? That is, how do I need to modify
this line: […]

for c in '1.32, 5.32, 4.4, 3.78':

[…] to find the total of these given numbers.


The original script already does not do what it advertises.  Instead, it
iterates over the characters of the string, attempts to convert each to an
integer and then computes the sum.  That is _not_ “calculate the total of
numbers given in a string”.

A solution has been presented, but it is not very pythonic because the
original code was not; that should have been

### Ahh, Gauß ;-)
print(sum(map(lambda x: int(x), list('0123456789'
### 

Also, it cannot handle non-numeric strings well.  Consider this instead:

### 
from re import findall

s = '1.32, 5.32, 4.4, 3.78'
print(sum(map(lambda x: float(x), findall(r'-?\d+\.\d+', s
### 

But if you are sure that except for the comma separator there are only
numeric strings, it is more efficient to use re.split() instead of
re.findall() here.


Aside:

I thought I had more than a fair grasp of regular expressions, but I am
puzzled by

| $ python3
| Python 3.4.2 (default, Dec 27 2014, 13:16:08)
| [GCC 4.9.2] on linux
|  from re import findall
|  s = '1.32, 5.32, 4.4, 3.78'
|  findall(r'-?\d+(\.\d+)?', s)
| ['.32', '.32', '.4', '.78']

Why does this more flexible pattern not work as I expected in Python 3.x,
but virtually everywhere else?

And why this?

|  findall(r'-?\d+\.\d+', s)
| ['1.32', '5.32', '4.4', '3.78']
|  findall(r'-?\d+(\.\d+)', s)
| ['.32', '.32', '.4', '.78']

Feature?  Bug?



I can't tell you as I avoid regexes like I avoid the plague.  Having 
said that I do know that there loads of old bugs on the bug tracker, 
many of which are fixed in the new regex module that's available here 
https://pypi.python.org/pypi/regex/


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Thomas 'PointedEars' Lahn
Mark Lawrence wrote:

 On 11/01/2015 23:07, Thomas 'PointedEars' Lahn wrote:
 I thought I had more than a fair grasp of regular expressions, but I am
 puzzled by

 | $ python3
 | Python 3.4.2 (default, Dec 27 2014, 13:16:08)
 | [GCC 4.9.2] on linux
 |  from re import findall
 |  s = '1.32, 5.32, 4.4, 3.78'
 |  findall(r'-?\d+(\.\d+)?', s)
 | ['.32', '.32', '.4', '.78']

 Why does this more flexible pattern not work as I expected in Python 3.x,
 but virtually everywhere else?

 And why this?

 |  findall(r'-?\d+\.\d+', s)
 | ['1.32', '5.32', '4.4', '3.78']
 |  findall(r'-?\d+(\.\d+)', s)
 | ['.32', '.32', '.4', '.78']

 Feature?  Bug?
 
 I can't tell you

I know now why I get this result.  It is a feature, not a bug:

https://docs.python.org/3/library/re.html?highlight=findall#re.findall
|
| re.findall(pattern, string, flags=0)
|   Return all non-overlapping matches of pattern in string, as a list of 
|   strings. The string is scanned left-to-right, and matches are returned 
|   in the order found. If one or more groups are present in the pattern,

|   return a list of groups; this will be a list of tuples if the pattern
^^^   
|   has more than one group. Empty matches are included in the result unless 
|   they touch the beginning of another match.

A solution is to use non-capturing parentheses:

|  findall(r'-?\d+(?:\.\d+)?', '1.32, 5.32, 4.4, 3.78')
| ['1.32', '5.32', '4.4', '3.78']

 as I avoid regexes like I avoid the plague.

You should reconsider.  Regular expressions are a powerful tool.

 Having said that I do know that there loads of old bugs on the bug 
 tracker, many of which are fixed in the new regex module that's 
 available here https://pypi.python.org/pypi/regex/

Interesting, thank you.

Please trim your quotes to the relevant minimum next time, though.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Chris Angelico
On Mon, Jan 12, 2015 at 11:09 AM, Peter Otten __pete...@web.de wrote:

   print(sum(map(lambda x: float(x), s.split(',')))

 Please trim your quotes to the relevant minimum.

 Hm, can you explain what this

 lambda x: float(x)

 is supposed to achieve? I mean other than to confuse a newbie...

Maybe he gets paid by the character.

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


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Thomas 'PointedEars' Lahn
Joel Goldstick wrote:

 my_list = 1.23, 2.4, 3.123.split(,)
 
 that will give you ['1.23', '2.4', '3.123']

No, it gives

| $ python
| Python 2.7.9 (default, Dec 11 2014, 08:58:12) 
| [GCC 4.9.2] on linux2
| Type help, copyright, credits or license for more information.
|  my_list = 1.23, 2.4, 3.123.split(,)
|  my_list
| ['1.23', ' 2.4', ' 3.123']
| 

| $ python3
| Python 3.4.2 (default, Dec 27 2014, 13:16:08) 
| [GCC 4.9.2] on linux
| Type help, copyright, credits or license for more information.
|  my_list = 1.23, 2.4, 3.123.split(,)
|  my_list
| ['1.23', ' 2.4', ' 3.123']
|  

In order to get the result you described, one needs at least

|  '1.23, 2.4, 3.123'.split(', ')
| ['1.23', '2.4', '3.123']

This is safer:

|  from re import split
|  split(r'\s*,\s*', '1.23, 2.4, 3.123')
| ['1.23', '2.4', '3.123']

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Thomas 'PointedEars' Lahn
Joel Goldstick wrote:

 Thomas 'PointedEars' Lahn wrote:
 Joel Goldstick wrote:
 my_list = 1.23, 2.4, 3.123.split(,)

 that will give you ['1.23', '2.4', '3.123']

 No, it gives

 […]
 |  my_list = 1.23, 2.4, 3.123.split(,)
 |  my_list
 | ['1.23', ' 2.4', ' 3.123']
   ^   ^
 | 

 In order to get the result you described, one needs at least

 |  '1.23, 2.4, 3.123'.split(', ')
 | ['1.23', '2.4', '3.123']

 […]
 
 I'm not sure what you are trying to point out as your examples confirm
 my code.

No, they don't.

 Am I missing something.
^
(Is that a question.)

You are missing a leading space character because in the string the comma 
was followed by one.

 As for feeding a beginner regex solutions, I'm on the side that this
 is a terrible idea.  Regex is not something a beginner should worry
 about!

NAK.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread MRAB

On 2015-01-12 00:04, Mark Lawrence wrote:

On 11/01/2015 23:07, Thomas 'PointedEars' Lahn wrote:

Store Makhzan wrote:


I have this script which can calculate the total of numbers given in a
string […]
total = 0
for c in '0123456789':
total += int(c)
print total

[…]
How should I modify this script to find the total of if the numbers given
in the string form have decimal places? That is, how do I need to modify
this line: […]

for c in '1.32, 5.32, 4.4, 3.78':

[…] to find the total of these given numbers.


The original script already does not do what it advertises.  Instead, it
iterates over the characters of the string, attempts to convert each to an
integer and then computes the sum.  That is _not_ “calculate the total of
numbers given in a string”.

A solution has been presented, but it is not very pythonic because the
original code was not; that should have been

### Ahh, Gauß ;-)
print(sum(map(lambda x: int(x), list('0123456789'
### 

Also, it cannot handle non-numeric strings well.  Consider this instead:

### 
from re import findall

s = '1.32, 5.32, 4.4, 3.78'
print(sum(map(lambda x: float(x), findall(r'-?\d+\.\d+', s
### 

But if you are sure that except for the comma separator there are only
numeric strings, it is more efficient to use re.split() instead of
re.findall() here.


Aside:

I thought I had more than a fair grasp of regular expressions, but I am
puzzled by

| $ python3
| Python 3.4.2 (default, Dec 27 2014, 13:16:08)
| [GCC 4.9.2] on linux
|  from re import findall
|  s = '1.32, 5.32, 4.4, 3.78'
|  findall(r'-?\d+(\.\d+)?', s)
| ['.32', '.32', '.4', '.78']

Why does this more flexible pattern not work as I expected in Python 3.x,
but virtually everywhere else?

And why this?

|  findall(r'-?\d+\.\d+', s)
| ['1.32', '5.32', '4.4', '3.78']
|  findall(r'-?\d+(\.\d+)', s)
| ['.32', '.32', '.4', '.78']

Feature?  Bug?



I can't tell you as I avoid regexes like I avoid the plague.  Having
said that I do know that there loads of old bugs on the bug tracker,
many of which are fixed in the new regex module that's available here
https://pypi.python.org/pypi/regex/


It's not a bug.

re.findall returns the capture groups, if present, or the entire match
if there are no capture groups.

In this instance, it's better to use a non-capture group:

findall(r'-?\d+(?:\.\d+)', s)

It's all in the docs! :-)
--
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Joel Goldstick
On Sun, Jan 11, 2015 at 5:20 PM, Thomas 'PointedEars' Lahn
pointede...@web.de wrote:
 Joel Goldstick wrote:

 my_list = 1.23, 2.4, 3.123.split(,)

 that will give you ['1.23', '2.4', '3.123']

 No, it gives

 | $ python
 | Python 2.7.9 (default, Dec 11 2014, 08:58:12)
 | [GCC 4.9.2] on linux2
 | Type help, copyright, credits or license for more information.
 |  my_list = 1.23, 2.4, 3.123.split(,)
 |  my_list
 | ['1.23', ' 2.4', ' 3.123']
 | 

 | $ python3
 | Python 3.4.2 (default, Dec 27 2014, 13:16:08)
 | [GCC 4.9.2] on linux
 | Type help, copyright, credits or license for more information.
 |  my_list = 1.23, 2.4, 3.123.split(,)
 |  my_list
 | ['1.23', ' 2.4', ' 3.123']
 | 

 In order to get the result you described, one needs at least

 |  '1.23, 2.4, 3.123'.split(', ')
 | ['1.23', '2.4', '3.123']

 This is safer:

 |  from re import split
 |  split(r'\s*,\s*', '1.23, 2.4, 3.123')
 | ['1.23', '2.4', '3.123']


I'm not sure what you are trying to point out as your examples confirm
my code.  Am I missing something.

As for feeding a beginner regex solutions, I'm on the side that this
is a terrible idea.  Regex is not something a beginner should worry
about!
 --
 PointedEars

 Twitter: @PointedEars2
 Please do not cc me. / Bitte keine Kopien per E-Mail.
 --
 https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Peter Otten
Thomas 'PointedEars' Lahn wrote:

 Joel Goldstick wrote:
 
 On Sun, Jan 11, 2015 at 6:12 PM, Thomas 'PointedEars' Lahn
 pointede...@web.de wrote:
 Joel Goldstick wrote:
 Am I missing something.
^
 […]
 You are missing a leading space character because in the string the
 comma was followed by one.
 
 I see that now.  Performing float on each element of the list will
 take care of that, or I guess .strip() on each first.
 
 As I showed, .strip() is unnecessary.  But float() is always necessary for
 computing the sum and suffices indeed together with s.split() if s is just
 a comma-separated list of numeric strings with optional whitespace leading
 and trailing the comma:
 
   print(sum(map(lambda x: float(x), s.split(',')))
 
 Please trim your quotes to the relevant minimum.

Hm, can you explain what this

lambda x: float(x)

is supposed to achieve? I mean other than to confuse a newbie...


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


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Joel Goldstick
On Sun, Jan 11, 2015 at 3:26 PM, Store Makhzan stor...@gmail.com wrote:
 On Sunday, January 11, 2015 at 2:06:54 PM UTC-6, Joel Goldstick wrote:
 On Sun, Jan 11, 2015 at 2:31 PM, Store Makhzan wrote:
  I have this script which can calculate the total of numbers given in a 
  string
   script -
  total = 0
  for c in '0123456789':
 total += int(c)
  print total
   script -
 
  How should I modify this script to find the total of if the numbers given 
  in the string form have decimal places? That is, how do I need to modify 
  this line:
  - script -
  for c in '1.32, 5.32, 4.4, 3.78':
  - script -
  to find the total of these given numbers.
  --
  https://mail.python.org/mailman/listinfo/python-list

 split the string on ',' to get a list of strings.  loop thru list
 using float(s), add float values


 --
 Joel Goldstick
 http://joelgoldstick.com

 Thank you
 Here is what I did:

 - script -
 #Check if a perfect cube
 total = 0
 for c in ('1.23', '2.4', '3.123'):
print float(c)
total += float(c)
 print total
 - script -

 Which gave me the result I wanted.
 Since I am new to Python, I used () as a guess, and it worked.

That's fine, but its different than your original question.  In your
original question you had a string of floats separated by commas.  To
solve that problem you need to first split the string on the commas:

my_list = 1.23, 2.4, 3.123.split(,)

that will give you ['1.23', '2.4', '3.123']

From there do what you did starting with your for loop



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



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Steven D'Aprano
Thomas 'PointedEars' Lahn wrote:

 The original script already does not do what it advertises.  Instead, it
 iterates over the characters of the string, attempts to convert each to an
 integer and then computes the sum.  That is _not_ “calculate the total of
 numbers given in a string”.

Yes, and the second piece of code the Original Poster provided is even
worse:

#Check if a perfect cube
total = 0
for c in ('1.23', '2.4', '3.123'):
   print float(c)
   total += float(c)
print total


I don't see how adding up some numbers checks whether it is a perfect cube.
I guess this is a good example of this:

At Resolver we've found it useful to short-circuit any doubt 
and just refer to comments in code as 'lies'.

http://import-that.dreamwidth.org/956.html



 A solution has been presented, but it is not very pythonic because the
 original code was not; that should have been
 
 ### Ahh, Gauß ;-)
 print(sum(map(lambda x: int(x), list('0123456789'

That can be simplified to:

sum(map(int, '0123456789'))

which can then be passed to print() if required.



 Also, it cannot handle non-numeric strings well.  Consider this instead:

The OP hasn't specified whether or not he has to deal with non-numeric
strings, or how he wants to deal with them. But my guess is that he
actually doesn't want strings at all, and needs to be taught how to work
with lists of floats and/or ints.


 ### 
 from re import findall
 
 s = '1.32, 5.32, 4.4, 3.78'
 print(sum(map(lambda x: float(x), findall(r'-?\d+\.\d+', s
 ### 

Consider this:

py s = '123^%#@1.2abc, %#$@2.1*%^'
py print(sum(map(lambda x: float(x), findall(r'-?\d+\.\d+', s
3.3

If your aim is just to hide the fact that you have bad data, then the regex
solution works. Many beginners think that their job as a programmer is to
stop the program from raising an exception no matter what. But I suggest
that Postel's Law:

Be conservative in what you emit, and liberal in what you accept.

shouldn't apply here. I don't think any reasonable person would expect that
the string 123^%#@1.2abc should be treated as 1.2.


 Aside:
 
 I thought I had more than a fair grasp of regular expressions, but I am
 puzzled by
 
 | $ python3
 | Python 3.4.2 (default, Dec 27 2014, 13:16:08)
 | [GCC 4.9.2] on linux
 |  from re import findall
 |  s = '1.32, 5.32, 4.4, 3.78'
 |  findall(r'-?\d+(\.\d+)?', s)
 | ['.32', '.32', '.4', '.78']
 
 Why does this more flexible pattern not work as I expected in Python 3.x,
 but virtually everywhere else?

This is documented by findall:


py help(findall)
Help on function findall in module re:

findall(pattern, string, flags=0)
Return a list of all non-overlapping matches in the string.

If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.

Empty matches are included in the result.



-- 
Steven

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


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Thomas 'PointedEars' Lahn
Store Makhzan wrote:

 I have this script which can calculate the total of numbers given in a
 string […]
 total = 0
 for c in '0123456789':
total += int(c)
 print total
 
 […]
 How should I modify this script to find the total of if the numbers given
 in the string form have decimal places? That is, how do I need to modify
 this line: […]
 
 for c in '1.32, 5.32, 4.4, 3.78':
 
 […] to find the total of these given numbers.

The original script already does not do what it advertises.  Instead, it 
iterates over the characters of the string, attempts to convert each to an 
integer and then computes the sum.  That is _not_ “calculate the total of 
numbers given in a string”.

A solution has been presented, but it is not very pythonic because the 
original code was not; that should have been

### Ahh, Gauß ;-)
print(sum(map(lambda x: int(x), list('0123456789'
### 

Also, it cannot handle non-numeric strings well.  Consider this instead:

### 
from re import findall

s = '1.32, 5.32, 4.4, 3.78'
print(sum(map(lambda x: float(x), findall(r'-?\d+\.\d+', s
### 

But if you are sure that except for the comma separator there are only 
numeric strings, it is more efficient to use re.split() instead of 
re.findall() here.


Aside:

I thought I had more than a fair grasp of regular expressions, but I am 
puzzled by

| $ python3
| Python 3.4.2 (default, Dec 27 2014, 13:16:08) 
| [GCC 4.9.2] on linux
|  from re import findall
|  s = '1.32, 5.32, 4.4, 3.78'
|  findall(r'-?\d+(\.\d+)?', s)
| ['.32', '.32', '.4', '.78']

Why does this more flexible pattern not work as I expected in Python 3.x, 
but virtually everywhere else?

And why this?

|  findall(r'-?\d+\.\d+', s)
| ['1.32', '5.32', '4.4', '3.78']
|  findall(r'-?\d+(\.\d+)', s)
| ['.32', '.32', '.4', '.78']

Feature?  Bug?

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Grant Edwards
On 2015-01-11, Joel Goldstick joel.goldst...@gmail.com wrote:

 That's fine, but its different than your original question.  In your
 original question you had a string of floats separated by commas.  To
 solve that problem you need to first split the string on the commas:

 my_list = 1.23, 2.4, 3.123.split(,)

 that will give you ['1.23', '2.4', '3.123']

Well, almost:

$ python
Python 2.7.9 (default, Jan 11 2015, 15:39:24) 
[GCC 4.7.3] on linux2
Type help, copyright, credits or license for more information.
 1.23, 2.4, 3.123.split(,)
['1.23', ' 2.4', ' 3.123']

Note the leating whitespace in two of the elements. In this case, the
leading whitespace is ignored if you pass the values to float():

map(float,1.23, 2.4, 3.123.split(,))
[1.23, 2.4, 3.123]

Or for you young folks who prefer the more long-winded version:

 [float(s) for s in 1.23, 2.4, 3.123.split(,)]
[1.23, 2.4, 3.123]

In other situations, the leading whitespace might matter.

-- 
Grant



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


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Steven D'Aprano
Thomas 'PointedEars' Lahn wrote:

 This is safer:
 
 |  from re import split
 |  split(r'\s*,\s*', '1.23, 2.4, 3.123')
 | ['1.23', '2.4', '3.123']

Safer, slower, and unnecessary.

There is no need for the nuclear-powered bulldozer of regular expressions
just to crack this tiny peanut. We can split on commas, and then strip
whitespace:

py values = 1.234   ,4.5678,   9.0123  ,4.321,0.9876  
py [s.strip() for s in values.split(',')]
['1.234', '4.5678', '9.0123', '4.321', '0.9876']


but in fact, we don't even need that, since float is perfectly happy to
accept strings with leading and trailing spaces:

py float('1.2345  ')
1.2345


-- 
Steven

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


Re: extracting numbers with decimal places from a string

2015-01-11 Thread Thomas 'PointedEars' Lahn
Peter Otten wrote:

 Thomas 'PointedEars' Lahn wrote:
 […]  But float() is always necessary for computing the sum and suffices 
 indeed together with s.split() if s is just a comma-separated list of 
 numeric strings with optional whitespace leading and trailing the comma:
 
   print(sum(map(lambda x: float(x), s.split(',')))
 
 Please trim your quotes to the relevant minimum.
   
 Hm, can you explain what this
 
 lambda x: float(x)
 
 is supposed to achieve? I mean other than to confuse a newbie...

  print(sum(map(float, s.split(','

suffices in this case, of course.

I could have done without the snide remarks.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: decimal numbers

2014-02-16 Thread wxjmfauth
Without any warranty.

 def z(r):
... # r: int  0
... t = log10(r)
... if t = 12.0:
... prefix = ''
... prefix2 = ''
... elif t = 9.0:
... prefix = 'giga'
... prefix2 = 'G'
... r = r / 1.0e9
... elif t = 6.0:
... prefix = 'mega'
... prefix2 = 'M'
... r = r / 1.0e6
... elif t = 3.0:
... prefix = 'kilo-'  # Netherlands std?
... prefix2 = 'k'
... r = r / 1.0e3
... else:
... prefix = ''
... prefix2 = ''
... 
... # correct for this language (Dutch?) ?
... # kept as illustrative example
... if r = 2:
... suffix = 's'
... else:
... suffix = ''
... 
... # '.13g' to cover the ranges while keeping precision
... num = format(r, '.13g')
... s = 'de weerstand is ' + num + ' ' + prefix + 'ohm' + suffix
... s = s + ' , R = ' + num + ' ' + prefix2 + 'Ω'
... return s
... 
 a = [1, 2, 9, 20, 300, 1000 - 1, 1000, 1000 + 1, 2000, \
... 100 - 1, 100, 100 + 1, \
... 10 - 1, 10, 10 + 1, 11123456789]
 
 for e in a:
... print(e, '-', z(e))
... 
1 - de weerstand is 1 ohm , R = 1 Ω
2 - de weerstand is 2 ohms , R = 2 Ω
9 - de weerstand is 9 ohms , R = 9 Ω
20 - de weerstand is 20 ohms , R = 20 Ω
300 - de weerstand is 300 ohms , R = 300 Ω
999 - de weerstand is 999 ohms , R = 999 Ω
1000 - de weerstand is 1 kilo-ohm , R = 1 kΩ
1001 - de weerstand is 1.001 kilo-ohm , R = 1.001 kΩ
2000 - de weerstand is 2 kilo-ohms , R = 2 kΩ
99 - de weerstand is 999.999 kilo-ohms , R = 999.999 kΩ
100 - de weerstand is 1 megaohm , R = 1 MΩ
101 - de weerstand is 1.01 megaohm , R = 1.01 MΩ
9 - de weerstand is 999.99 megaohms , R = 999.99 MΩ
10 - de weerstand is 1 gigaohm , R = 1 GΩ
11 - de weerstand is 1.1 gigaohm , R = 1.1 GΩ
11123456789 - de weerstand is 11.123456789 gigaohms , R = 11.123456789 GΩ

jmf

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


Re: decimal numbers

2014-02-15 Thread Luke Geelen
Op zaterdag 15 februari 2014 10:18:36 UTC+1 schreef Luke Geelen:
 hello,
 
 i have been working on a python resistor calculator to let my class show what 
 you can do with python.
 
 now i have a script that makes the more speekable value of the resistance 
 (res)
 
 
 
 #if len(str(res))  9:
 
 #  res2 = res / 10
 
 #  print de weerstand is %s,%s giga ohms % (res2)
 
 #elif len(str(res))  6:
 
 #  res2 = res / 100
 
 #  print de weerstand is %s,%s Mega ohm % (res2)
 
 #elif len(str(res))  3:
 
 #  res2 = res / 1000
 
 #  print de weerstand is, res2,kilo ohm
 
 #elif len(str(res))  4:
 
 #  res2 = res
 
 #  print de weerstand is, res2,ohm
 
 
 
 i commented it because it doesn't work (yet), when i have a resistance of 
 
 9.9 Giga ohms it says it is 9 giga ohms. it seems to work with natural 
 number, anyway of using decimals insted so that it says : the resistance is 
 9.9 Giga Ohms instead of 9 ?

, wait i have put one %s to much in the print function. this is from a other 
attempt so please excuse me
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: decimal numbers

2014-02-15 Thread Frank Millman

Luke Geelen luke.gee...@gmail.com wrote in message 
news:ec88852e-1384-4aa5-834b-85135be94...@googlegroups.com...
 Op zaterdag 15 februari 2014 10:18:36 UTC+1 schreef Luke Geelen:
 hello,

 i have been working on a python resistor calculator to let my class show 
 what you can do with python.

 now i have a script that makes the more speekable value of the resistance 
 (res)

[...]

 i commented it because it doesn't work (yet), when i have a resistance of

 9.9 Giga ohms it says it is 9 giga ohms. it seems to work with natural 
 number, anyway of using decimals insted so that it says : the resistance 
 is 9.9 Giga Ohms instead of 9 ?


You don't say which version of python you are using.

If you are using python2, an integer divided by an integer always returns an 
integer -

 10/3
3

It was changed in python3 to return a float -

 10/3
3.3335

You can reproduce the python3 behaviour in python2 by adding a 'future' 
directive -

 from __future__ import division
 10/3
3.3335

HTH

Frank Millman



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


Re: decimal numbers

2014-02-15 Thread Chris Angelico
On Sat, Feb 15, 2014 at 9:04 PM, Frank Millman fr...@chagford.com wrote:
 If you are using python2, an integer divided by an integer always returns an
 integer -

 10/3
 3

 It was changed in python3 to return a float -

 10/3
 3.3335

 You can reproduce the python3 behaviour in python2 by adding a 'future'
 directive -

 from __future__ import division
 10/3
 3.3335


Conversely, you can get an integer result by using floor division:

 10//3
3

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


Re: decimal numbers

2014-02-15 Thread Luke Geelen
Op zaterdag 15 februari 2014 11:04:17 UTC+1 schreef Frank Millman:
 Luke Geelen luke.gee...@gmail.com wrote in message 
 
 news:ec88852e-1384-4aa5-834b-85135be94...@googlegroups.com...
 
  Op zaterdag 15 februari 2014 10:18:36 UTC+1 schreef Luke Geelen:
 
  hello,
 
 
 
  i have been working on a python resistor calculator to let my class show 
 
  what you can do with python.
 
 
 
  now i have a script that makes the more speekable value of the resistance 
 
  (res)
 
 
 
 [...]
 
 
 
  i commented it because it doesn't work (yet), when i have a resistance of
 
 
 
  9.9 Giga ohms it says it is 9 giga ohms. it seems to work with natural 
 
  number, anyway of using decimals insted so that it says : the resistance 
 
  is 9.9 Giga Ohms instead of 9 ?
 
 
 
 
 
 You don't say which version of python you are using.
 
 
 
 If you are using python2, an integer divided by an integer always returns an 
 
 integer -
 
 
 
  10/3
 
 3
 
 
 
 It was changed in python3 to return a float -
 
 
 
  10/3
 
 3.3335
 
 
 
 You can reproduce the python3 behaviour in python2 by adding a 'future' 
 
 directive -
 
 
 
  from __future__ import division
 
  10/3
 
 3.3335
 
 
 
 HTH
 
 
 
 Frank Millman

how (and where) would i add this rule into a script? by import or the 
calculation?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: decimal numbers

2014-02-15 Thread Frank Millman

Luke Geelen luke.gee...@gmail.com wrote in message 
news:ae0da085-6c41-4166-92d2-92611a990...@googlegroups.com...
 Op zaterdag 15 februari 2014 11:04:17 UTC+1 schreef Frank Millman:
 Luke Geelen luke.gee...@gmail.com wrote in message

 news:ec88852e-1384-4aa5-834b-85135be94...@googlegroups.com...

[...]

 You can reproduce the python3 behaviour in python2 by adding a 'future' 
 directive -

  from __future__ import division

  10/3

 3.3335


 how (and where) would i add this rule into a script? by import or the 
 calculation?

Treat it like any other import - add it as a new line at the top of your 
script.

Frank



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


Re: decimal numbers

2014-02-15 Thread Frank Millman

Frank Millman fr...@chagford.com wrote in message 
news:ldngnf$c3r$1...@ger.gmane.org...

 Luke Geelen luke.gee...@gmail.com wrote in message 
 news:ae0da085-6c41-4166-92d2-92611a990...@googlegroups.com...
 Op zaterdag 15 februari 2014 11:04:17 UTC+1 schreef Frank Millman:
 Luke Geelen luke.gee...@gmail.com wrote in message

 news:ec88852e-1384-4aa5-834b-85135be94...@googlegroups.com...

 [...]

 You can reproduce the python3 behaviour in python2 by adding a 'future' 
 directive -

  from __future__ import division

  10/3

 3.3335


 how (and where) would i add this rule into a script? by import or the 
 calculation?

 Treat it like any other import - add it as a new line at the top of your 
 script.


Actually I did not answer that very accurately. From the documentation -


A future statement must appear near the top of the module. The only lines 
that can appear before a future statement are:

the module docstring (if any),
comments,
blank lines, and
other future statements.


Frank



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


Re: decimal numbers

2014-02-15 Thread Laurent Pointal
luke.gee...@gmail.com wrote:

 hello,
 i have been working on a python resistor calculator to let my class show
 what you can do with python. now i have a script that makes the more
 speekable value of the resistance (res)
 
 #if len(str(res))  9:
 #  res2 = res / 10
 #  print de weerstand is %s,%s giga ohms % (res2)
 #elif len(str(res))  6:
 #  res2 = res / 100
 #  print de weerstand is %s,%s Mega ohm % (res2)
 #elif len(str(res))  3:
 #  res2 = res / 1000
 #  print de weerstand is, res2,kilo ohm
 #elif len(str(res))  4:
 #  res2 = res
 #  print de weerstand is, res2,ohm
 
 i commented it because it doesn't work (yet), when i have a resistance of
 9.9 Giga ohms it says it is 9 giga ohms. it seems to work with natural
 number, anyway of using decimals insted so that it says : the resistance
 is 9.9 Giga Ohms instead of 9 ?

Seem you are using Python2, if res is an integer the division by an integer 
values produce an integer result (changed in Python3), so you loose the 
decimal part.

Try dividing by floating point numbers, like res2 = res / 1000.


Note: should take a lok at the log10() function from math module.

(with Python3)

In [1]: from math import log10

In [2]: r = 132828378723

In [3]: int(log10(r))
Out[3]: 11

In [4]: r / 10**int(log10(r))
Out[4]: 1.32828378723

A+
Laurent.

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


Re: decimal numbers

2014-02-15 Thread Luke Geelen
If i do set form thing in my script i get 
Invalide syntax pointing at the last word of the form rule
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: decimal numbers

2014-02-15 Thread Ian Kelly
On Sat, Feb 15, 2014 at 2:18 AM,  luke.gee...@gmail.com wrote:
 hello,
 i have been working on a python resistor calculator to let my class show what 
 you can do with python.
 now i have a script that makes the more speekable value of the resistance 
 (res)

 #if len(str(res))  9:
 #  res2 = res / 10
 #  print de weerstand is %s,%s giga ohms % (res2)
 #elif len(str(res))  6:
 #  res2 = res / 100
 #  print de weerstand is %s,%s Mega ohm % (res2)
 #elif len(str(res))  3:
 #  res2 = res / 1000
 #  print de weerstand is, res2,kilo ohm
 #elif len(str(res))  4:
 #  res2 = res
 #  print de weerstand is, res2,ohm

 i commented it because it doesn't work (yet), when i have a resistance of
 9.9 Giga ohms it says it is 9 giga ohms. it seems to work with natural 
 number, anyway of using decimals insted so that it says : the resistance is 
 9.9 Giga Ohms instead of 9 ?

Others have already explained how to do floating-point rather than
integer division.  I'm curious to know why you're basing the if tests
on the length of the number as a string rather than on the magnitude
of the number.  Consider for example an input of 0.01.  Converted to a
string, that is 0.01 which has a length of 4.  So the output would
be de weerstand is 0.1 kilo ohm, which is probably not what you
would desire.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: decimal numbers

2014-02-15 Thread Ian Kelly
On Sat, Feb 15, 2014 at 10:17 AM, Luke Geelen luke.gee...@gmail.com wrote:
 If i do set form thing in my script i get
 Invalide syntax pointing at the last word of the form rule

Please copy and paste the exact code you ran along with the full text
of the exception into your post.  Paraphrasing it like this doesn't
help us help you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: decimal numbers

2014-02-15 Thread Luke Geelen
Op zaterdag 15 februari 2014 18:23:20 UTC+1 schreef Ian:
 On Sat, Feb 15, 2014 at 10:17 AM, Luke Geelen luke.gee...@gmail.com wrote:
 
  If i do set form thing in my script i get
 
  Invalide syntax pointing at the last word of the form rule
 
 
 
 Please copy and paste the exact code you ran along with the full text
 
 of the exception into your post.  Paraphrasing it like this doesn't
 
 help us help you.

sorry i made a typo its fixed, thanks a lot
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: decimal numbers

2014-02-15 Thread Luke Geelen
Op zaterdag 15 februari 2014 18:42:51 UTC+1 schreef Luke Geelen:
 Op zaterdag 15 februari 2014 18:23:20 UTC+1 schreef Ian:
 
  On Sat, Feb 15, 2014 at 10:17 AM, Luke Geelen luke.gee...@gmail.com wrote:
 
  
 
   If i do set form thing in my script i get
 
  
 
   Invalide syntax pointing at the last word of the form rule
 
  
 
  
 
  
 
  Please copy and paste the exact code you ran along with the full text
 
  
 
  of the exception into your post.  Paraphrasing it like this doesn't
 
  
 
  help us help you.
 
 
 
 sorry i made a typo its fixed, thanks a lot

hey, is it possible to remove the .0 if it is a valua without something behind 
the poit (like 5.0 gets 5 but 9.9 stays 9.9
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: decimal numbers

2014-02-15 Thread Mark Lawrence

On 15/02/2014 18:57, Luke Geelen wrote:

Op zaterdag 15 februari 2014 18:42:51 UTC+1 schreef Luke Geelen:

Op zaterdag 15 februari 2014 18:23:20 UTC+1 schreef Ian:


On Sat, Feb 15, 2014 at 10:17 AM, Luke Geelen luke.gee...@gmail.com wrote:







If i do set form thing in my script i get







Invalide syntax pointing at the last word of the form rule















Please copy and paste the exact code you ran along with the full text







of the exception into your post.  Paraphrasing it like this doesn't







help us help you.




sorry i made a typo its fixed, thanks a lot


hey, is it possible to remove the .0 if it is a valua without something behind 
the poit (like 5.0 gets 5 but 9.9 stays 9.9



Thanks for yet more double line spacing and single line paragraphs.  Is 
it too much to ask for you to follow the instructions that you've 
already been given or better yet to use a decent tool?


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: decimal numbers

2014-02-15 Thread Steven D'Aprano
On Sat, 15 Feb 2014 10:57:20 -0800, Luke Geelen wrote:

 hey, is it possible to remove the .0 if it is a valua without something
 behind the poit (like 5.0 gets 5 but 9.9 stays 9.9

Yes, but not easily. First, check the number's fractional part, and if it 
is zero, convert it to an int:

# Here, your value is x
if x % 1 == 0:
# Exact whole number.
x = int(x)


But be warned that really big floats are always ints, even if they have a 
decimal point in them! For example:

x = 1.1e20

has a decimal point, but its value is:

11000.0

which is a whole number. So perhaps a better way to do this is to operate 
on the number as a string, not as a numeric value:

s = %s % x
if s.endswith(.0):
s = s[:-2]


If there is anything you don't understand about this code snippet, please 
feel free to ask.

By the way, I see that you are using GoogleGroups to post. GoogleGroups 
has an extremely obnoxious and annoying habit of throwing in blank lines 
between every line of your reply. Could you please read and follow the 
instructions here:

https://wiki.python.org/moin/GoogleGroupsPython


otherwise you are likely to annoy people and may find we stop answering 
your questions. We are volunteers, and aren't being paid to answer your 
questions. If you make it difficult for us, we may just stop.

Thank you in advance.

Any questions, please don't hesitate to ask.



-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: decimal numbers

2014-02-15 Thread Ian Kelly
On Sat, Feb 15, 2014 at 11:57 AM, Luke Geelen luke.gee...@gmail.com wrote:
 hey, is it possible to remove the .0 if it is a valua without something 
 behind the poit (like 5.0 gets 5 but 9.9 stays 9.9

The ':g' format specifier will trim off trailing zeroes, e.g.:

 '{:g}'.format(5.0)
'5'

It also switches to exponential notation if the scale of the number is
greater than the specified precision (default 6):

 '{:g}'.format(500.0)
'5e+06'

You can read up on string formatting for more details:
http://docs.python.org/3/library/string.html#formatstrings
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: decimal numbers

2014-02-15 Thread Steven D'Aprano
On Sat, 15 Feb 2014 14:34:45 -0700, Ian Kelly wrote:

 On Sat, Feb 15, 2014 at 11:57 AM, Luke Geelen luke.gee...@gmail.com
 wrote:
 hey, is it possible to remove the .0 if it is a valua without something
 behind the poit (like 5.0 gets 5 but 9.9 stays 9.9
 
 The ':g' format specifier will trim off trailing zeroes, e.g.:
 
 '{:g}'.format(5.0)
 '5'

Oh! That's much nicer than my solution. And it even works with %-style 
string interpolation too!

py %g % 23.0
'23'
py %g % 23.1
'23.1'


Even though I didn't ask the question, I learned something from the 
answer. Thank you.



-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: decimal numbers

2014-02-15 Thread Chris Angelico
On Sun, Feb 16, 2014 at 1:30 PM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 Even though I didn't ask the question, I learned something from the
 answer. Thank you.

Reason #1443694 for mailing lists rather than personal tutoring :) I
love this aspect of them.

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


Re: Floating numbers

2010-08-13 Thread Mark Dickinson
On Aug 12, 9:43 pm, Bradley Hintze bradle...@aggiemail.usu.edu
wrote:
 Hi all.

 Is there a way I can keep my floating point number as I typed it? For
 example, I want 34.52 to be 34.52 and NOT 34.520002.

Nitpick: unless you're on very unusual hardware, you're missing some
zeros here.  On my machine, under Python 2.6, the float 34.52 displays
as 34.523, and the value stored internally is actually
34.5231263880373081783294677734375;  so that's within
1 part in 10**16 of the value you entered.

Why do you care?  That's a serious question, and its answer goes a
long way to determining what you should do.

 - If you're doing calculations with this number, then the difference
between the number Python stores and 34.52 is so miniscule that in
normal situations it's not going to matter.  In particular, if it
represents some physical quantity then any error in the representation
will be swamped by the inherent measurement error.  IOW, it's not
worth worrying about.

 - If you're printing this number, and you just want the output to
look nice (why?  perhaps because you're showing this to other
people?), then use float formatting operations to limit the number of
decimal places you're printing.  For example, '%.6f' % my_float, or
format(my_float, '.6f'), will give my_float to 6 places after the
decimal point.  Or, as others have mentioned, it just so happens that
Python 2.7 and 3.x will output a nice representation for this float
automatically.  That wouldn't necessarily be true if the result were
coming from a calculation, though, so you shouldn't rely on repr
producing nice results in those versions of Python.

 - If you *really* need a number that represents the *exact* value
34.52, then use the decimal module, or perhaps consider using a simple
home-brewed fixed-point representation.  One situation where you might
care is when doing financial calculations, and in particular when
rounding a quantity to a smaller number of decimal digits.  Here
binary floats can give unpredictable results in halfway cases. (E.g.,
round(2.675, 2) might give 2.68 or 2.67, depending on what version of
Python you're using, and also possibly depending on your platforms.)

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


Re: Floating numbers

2010-08-13 Thread jmfauth
A quick question.

I understand how to get these numbers

34.5231263880373081783294677734375

and

47 (from 2**47)

and the sign.

with the decimal module, but I fail to find this one

4858258098025923

Possible?



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


Re: Floating numbers

2010-08-13 Thread Mark Dickinson
On Aug 13, 3:03 pm, jmfauth wxjmfa...@gmail.com wrote:
 A quick question.

 I understand how to get these numbers

 34.5231263880373081783294677734375

 and

 47 (from 2**47)

 and the sign.

 with the decimal module, but I fail to find this one

 4858258098025923

 Possible?

See the float.as_integer_ratio method.

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


Re: Floating numbers

2010-08-13 Thread jmfauth
On 13 août, 17:43, Mark Dickinson dicki...@gmail.com wrote:
 On Aug 13, 3:03 pm, jmfauth wxjmfa...@gmail.com wrote:



  A quick question.

  I understand how to get these numbers

  34.5231263880373081783294677734375

  and

  47 (from 2**47)

  and the sign.

  with the decimal module, but I fail to find this one

  4858258098025923

  Possible?

 See the float.as_integer_ratio method.

 --
 Mark


Thanks. I *stupidely* forget this.

jmf

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


Re: Floating numbers

2010-08-13 Thread Aahz
In article 595969e7-354f-456d-82b5-6aeafbabe...@d8g2000yqf.googlegroups.com,
Mark Dickinson  dicki...@gmail.com wrote:

 - If you *really* need a number that represents the *exact* value
34.52, then use the decimal module, or perhaps consider using a simple
home-brewed fixed-point representation.  

Don't use a home-brew fixed-point, rely on Uncle Tim!

http://pythoncraft.com/FixedPoint.py
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

...if I were on life-support, I'd rather have it run by a Gameboy than a
Windows box.  --Cliff Wells
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating numbers

2010-08-12 Thread Gary Herron

On 08/12/2010 01:43 PM, Bradley Hintze wrote:

Hi all.

Is there a way I can keep my floating point number as I typed it? For
example, I want 34.52 to be 34.52 and NOT 34.520002.

   



Is this a Python question?


The answer is both Yes and No. The binary floating point representation 
of numbers on a computer cannot exactly represent most decimal number 
you would like to type. (Similar to the fact that you cannot represent 
1/3 exactly in a decimal system.)


But that's the internal representation, over which you have no control. 
You do, however, have control over how a number is displayed when printed.


Python 2: Choose a format that displays the exact number of digits you want
'%.2f' % a
or let str(a) choose
but not repr(a) which tries to get all the digits.
(Adding to the confusion, you might also find it confusing to understand 
which of str() or repr() Python chooses to display a number.)


Python 3: Python3 uses David Gay’s algorithm for chosing how to display 
floats. Both str(a) and repr(a) produce '34.52' for your example, which 
is probably just what you want.



Gary Herron


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


Re: Floating numbers

2010-08-12 Thread Grant Edwards
On 2010-08-12, Bradley Hintze bradle...@aggiemail.usu.edu wrote:

 Is there a way I can keep my floating point number as I typed it?

No.

 For example, I want 34.52 to be 34.52 and NOT 34.520002.

You can't represent 34.52 using base-2 IEEE floating point (the HW
floating point format used by pretty much all modern computers).
34.520002 is as close as you can get.

When you enter a base-10 floating-point number, the computer will use
the closest base-2 IEEE floating point number.

Here are the nitty-gritty details:

  http://docs.sun.com/source/806-3568/ncg_goldberg.html

Can you explain what your actual problem is?
  
-- 
Grant Edwards   grant.b.edwardsYow! I'm imagining a surfer
  at   van filled with soy sauce!
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating numbers

2010-08-12 Thread Grant Edwards
On 2010-08-12, Grant Edwards inva...@invalid.invalid wrote:
 On 2010-08-12, Bradley Hintze bradle...@aggiemail.usu.edu wrote:

 Is there a way I can keep my floating point number as I typed it?

 No.

 For example, I want 34.52 to be 34.52 and NOT 34.520002.

 You can't represent 34.52 using base-2 IEEE floating point (the HW
 floating point format used by pretty much all modern computers).
 34.520002 is as close as you can get.

 When you enter a base-10 floating-point number, the computer will use
 the closest base-2 IEEE floating point number.

 Here are the nitty-gritty details:

   http://docs.sun.com/source/806-3568/ncg_goldberg.html

Here is a gentler intro:

 http://pyfaq.infogami.com/why-are-floating-point-calculations-so-inaccurate

-- 
Grant Edwards   grant.b.edwardsYow! If I felt any more
  at   SOPHISTICATED I would DIE
  gmail.comof EMBARRASSMENT!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating numbers

2010-08-12 Thread Philip Semanchuk


On Aug 12, 2010, at 4:43 PM, Bradley Hintze wrote:


Hi all.

Is there a way I can keep my floating point number as I typed it? For
example, I want 34.52 to be 34.52 and NOT 34.520002.


Hi Bradley,
Use the Decimal type instead. It's not as convenient as float, but it  
will give you a consistent representation of your numbers.


The behavior of floating point numbers surprises a lot of people and  
has been discussed at length a number of times here (and elsewhere).


If you're in the mood for EXTREMELY thorough coverage of the subject,  
you can read this:

http://docs.sun.com/source/806-3568/ncg_goldberg.html

There's a gentler discussion of it here:
http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding

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


Re: Floating numbers

2010-08-12 Thread Thomas Jollans
On Thursday 12 August 2010, it occurred to Bradley Hintze to exclaim:
 Hi all.
 
 Is there a way I can keep my floating point number as I typed it? For
 example, I want 34.52 to be 34.52 and NOT 34.520002.

The conversion from decimal to binary and vice versa is inexact -- but they're 
the same number internally:
 
Python 2.6.6rc1+ (r266rc1:83691, Aug  5 2010, 17:07:04) 
[GCC 4.4.5 20100728 (prerelease)] on linux2
Type help, copyright, credits or license for more information.
 34.52
34.523
 34.523 == 34.52
True
 


Python 3 is a bit smarter when printing, so you don't really notice what's 
going on:

Python 3.1.2 (release31-maint, Jul  8 2010, 09:18:08) 
[GCC 4.4.4] on linux2
Type help, copyright, credits or license for more information.
 34.52
34.52
 34.523
34.52
 

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


Re: Floating numbers

2010-08-12 Thread Chris Rebert
On Thu, Aug 12, 2010 at 1:43 PM, Bradley Hintze
bradle...@aggiemail.usu.edu wrote:
 Hi all.

 Is there a way I can keep my floating point number as I typed it? For
 example, I want 34.52 to be 34.52 and NOT 34.520002.

stuff repeating Gary's answer redacted

See also: 
http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding

Another option is to use the `decimal` module, which *can* exactly
represent decimal numbers (to a user-specified finite precision) and
is generally a bit more intuitive but /substantially/ slower:
http://docs.python.org/library/decimal.html

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


Re: Floating numbers

2010-08-12 Thread Grant Edwards
On 2010-08-12, Grant Edwards inva...@invalid.invalid wrote:

 Here are the nitty-gritty details:

   http://docs.sun.com/source/806-3568/ncg_goldberg.html

 Here is a gentler intro:

  http://pyfaq.infogami.com/why-are-floating-point-calculations-so-inaccurate

And another good page:

  http://docs.python.org/tutorial/floatingpoint.html

-- 
Grant Edwards   grant.b.edwardsYow! I feel like I'm
  at   in a Toilet Bowl with a
  gmail.comthumbtack in my forehead!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating numbers

2010-08-12 Thread Christian Heimes
 Is there a way I can keep my floating point number as I typed it? For
 example, I want 34.52 to be 34.52 and NOT 34.520002.

This isn't a Python issue. Python uses IEEE 754 [1] double precision
floats like most other languages. 34.52 can't be stored in a float. The
next valid float is 34.520002.

Christian

[1] http://en.wikipedia.org/wiki/IEEE_754

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


Re: Floating numbers

2010-08-12 Thread Ned Deily
In article i41p6e$1f...@dough.gmane.org,
 Christian Heimes li...@cheimes.de wrote:
 Is there a way I can keep my floating point number as I typed it? For
 example, I want 34.52 to be 34.52 and NOT 34.520002. 
 This isn't a Python issue. Python uses IEEE 754 [1] double precision
 floats like most other languages. 34.52 can't be stored in a float. The
 next valid float is 34.520002.

Well, it is a *bit* of a Python issue since, as others have pointed out, 
Python's behavior has changed due to the implementation of Gay's 
rounding algorithm in 3.1 and also in 2.7:

$ python2.6 -c 'print(repr(34.52))'
34.523
$ python2.7 -c 'print(repr(34.52))'
34.52
$ python3.1 -c 'print(repr(34.52))'
34.52

-- 
 Ned Deily,
 n...@acm.org

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


Re: Floating numbers

2010-08-12 Thread Benjamin Kaplan
On Thu, Aug 12, 2010 at 6:14 PM, Ned Deily n...@acm.org wrote:
 In article i41p6e$1f...@dough.gmane.org,
  Christian Heimes li...@cheimes.de wrote:
 Is there a way I can keep my floating point number as I typed it? For
 example, I want 34.52 to be 34.52 and NOT 34.520002.
 This isn't a Python issue. Python uses IEEE 754 [1] double precision
 floats like most other languages. 34.52 can't be stored in a float. The
 next valid float is 34.520002.

 Well, it is a *bit* of a Python issue since, as others have pointed out,
 Python's behavior has changed due to the implementation of Gay's
 rounding algorithm in 3.1 and also in 2.7:

 $ python2.6 -c 'print(repr(34.52))'
 34.523
 $ python2.7 -c 'print(repr(34.52))'
 34.52
 $ python3.1 -c 'print(repr(34.52))'
 34.52


But that's not keeping the number the way it was typed. It's just not
showing you the exact approximation. It doesn't get rid of rounding
errors.
 34.52
34.52
  _ * 10**10
3452.6

 --
  Ned Deily,
  ...@acm.org

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

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


Re: Floating numbers

2010-08-12 Thread Ned Deily
In article 
aanlkti=kom3xbknmmvwbhxxsvnya_kucokbnpzqp2...@mail.gmail.com,
 Benjamin Kaplan benjamin.kap...@case.edu wrote:
  Well, it is a *bit* of a Python issue since, as others have pointed out,
  Python's behavior has changed due to the implementation of Gay's
  rounding algorithm in 3.1 and also in 2.7:
 
  $ python2.6 -c 'print(repr(34.52))'
  34.523
  $ python2.7 -c 'print(repr(34.52))'
  34.52
  $ python3.1 -c 'print(repr(34.52))'
  34.52
 But that's not keeping the number the way it was typed. It's just not
 showing you the exact approximation. It doesn't get rid of rounding
 errors.
  34.52
 34.52
   _ * 10**10
 3452.6

Yes, as discussed earlier in this thread and I didn't mean to imply 
otherwise.   I should have worded my comment differently: the main 
reason for making it was to point out that the new float repr format 
feature is also in 2.7.

-- 
 Ned Deily,
 n...@acm.org

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


Re: Floating numbers

2010-08-12 Thread Nobody
On Thu, 12 Aug 2010 18:19:40 -0700, Benjamin Kaplan wrote:

 But that's not keeping the number the way it was typed. It's just not
 showing you the exact approximation.

Nor is 34.523 showing you the exact approximation.

The closest double to 34.52 is 4858258098025923 / 2**47, whose exact
decimal representation is:

34.5231263880373081783294677734375

The decimal representation of 1/(2**n) for n0 always ends in 5. As a
consequence of this, the exact decimal representation of any binary
floating-point value which isn't itself an integer must end in 5.

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


Re: writing numbers in binary file

2010-05-31 Thread MRAB

eskandari wrote:

Hi,
I am a newbie in python. I have an data.pickle file which is
serialized form of an array of strings, I want to write their
offsets in another binary file, so an C++ program can read and analyse
them.
But when I try to write offset (number) in binary file, it raise
exception below in line  offsetfile.write(offset)
TypeError: argument 1 must be string or read-only buffer, not int

I search the internet, find that all suggest converting number to
string ---with str()---and then write string to file.
But I shouldn't do this. because the above mentioned C++ function,
read file with this assumption that there are numbers in file.
So I want to know, Is there any way to produce an binary file
containing numbers same as the way C++ does?
Can anybody help me?


You can't write ints to a file, but you can write bytestrings ('str' in
Python 2, 'bytes' in Python 3).

Use the 'struct' module to convert the int to a bytestring, and remember
to open the file as a binary file.
--
http://mail.python.org/mailman/listinfo/python-list


Re: writing numbers in binary file

2010-05-31 Thread Tim Chase

On 05/31/2010 10:56 AM, eskandari wrote:

But when I try to write offset (number) in binary file, it raise
exception below in line  offsetfile.write(offset)
TypeError: argument 1 must be string or read-only buffer, not int

I search the internet, find that all suggest converting number to
string ---with str()---and then write string to file.
But I shouldn't do this. because the above mentioned C++ function,
read file with this assumption that there are numbers in file.
So I want to know, Is there any way to produce an binary file
containing numbers same as the way C++ does?


Well, you have at least two options:

1) use the pack/unpack functions in the struct module to 
convert a number to a byte representation that you can then write 
to a file


2) write the number to the file as a string and then use C++ 
libraries to parse a number from a string.


In both cases, you have to consider what happens when the number 
is outside the bounds of your C++ data-type (you don't mention 
what you're using...an int, a long, or long long; signed vs. 
unsigned).  Additionally in the first case, you have to make sure 
that your memory-architecture (big-endian vs. little-endian) 
matches on both sides; or that you marshal the data through a 
pre-defined format (in libraries, commonly called network 
format).  For such reasons, I'd stick with method #2 unless you 
have a strong reason not to.


-tkc




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


Re: writing numbers in binary file

2010-05-31 Thread eskandari
On May 31, 12:30 pm, MRAB pyt...@mrabarnett.plus.com wrote:
 eskandari wrote:
  Hi,
  I am a newbie in python. I have an data.pickle file which is
  serialized form of an array of strings, I want to write their
  offsets in another binary file, so an C++ program can read and analyse
  them.
  But when I try to write offset (number) in binary file, it raise
  exception below in line  offsetfile.write(offset)
  TypeError: argument 1 must be string or read-only buffer, not int

  I search the internet, find that all suggest converting number to
  string ---with str()---and then write string to file.
  But I shouldn't do this. because the above mentioned C++ function,
  read file with this assumption that there are numbers in file.
  So I want to know, Is there any way to produce an binary file
  containing numbers same as the way C++ does?
  Can anybody help me?

 You can't write ints to a file, but you can write bytestrings ('str' in
 Python 2, 'bytes' in Python 3).

 Use the 'struct' module to convert the int to a bytestring, and remember
 to open the file as a binary file.

Thanks alot,
I have an question, if I do so, Will the second program (C++ program)
which process this file, encounter any problem while parsing the file?
It find number of integers by filelen/4 and . (It assumes that
file was created as the same way which C++ does)
Thanks in advance
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: writing numbers in binary file

2010-05-31 Thread Terry Reedy

On 5/31/2010 12:43 PM, eskandari wrote:

On May 31, 12:30 pm, MRABpyt...@mrabarnett.plus.com  wrote:

eskandari wrote:



Use the 'struct' module to convert the int to a bytestring, and remember
to open the file as a binary file.


Thanks alot,
I have an question, if I do so, Will the second program (C++ program)
which process this file, encounter any problem while parsing the file?
It find number of integers by filelen/4 and . (It assumes that
file was created as the same way which C++ does)


Tim Chase pretty well answered this. If you are not familiar with the 
problem of 'endianess', see

http://en.wikipedia.org/wiki/Endianess

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


Re: writing numbers in binary file

2010-05-31 Thread Dave Angel

eskandari wrote:

On May 31, 12:30 pm, MRAB pyt...@mrabarnett.plus.com wrote:
  

eskandari wrote:


Hi,
I am a newbie in python. I have an data.pickle file which is
serialized form of an array of strings, I want to write their
offsets in another binary file, so an C++ program can read and analyse
them.
But when I try to write offset (number) in binary file, it raise
exception below in line  offsetfile.write(offset)
TypeError: argument 1 must be string or read-only buffer, not int
  
I search the internet, find that all suggest converting number to

string ---with str()---and then write string to file.
But I shouldn't do this. because the above mentioned C++ function,
read file with this assumption that there are numbers in file.
So I want to know, Is there any way to produce an binary file
containing numbers same as the way C++ does?
Can anybody help me?
  

You can't write ints to a file, but you can write bytestrings ('str' in
Python 2, 'bytes' in Python 3).

Use the 'struct' module to convert the int to a bytestring, and remember
to open the file as a binary file.



Thanks alot,
I have an question, if I do so, Will the second program (C++ program)
which process this file, encounter any problem while parsing the file?
It find number of integers by filelen/4 and . (It assumes that
file was created as the same way which C++ does)
Thanks in advance

  
You talk as if C++ has a single way to write a file, or read a file.  It 
has dozens of possibilities, as does Python.  In another message, you 
refer to four bytes per number, so it's possible you're talking about 
reading directly from the file into an int variable.  If you know that 
the C++ program is reading a file in mode 'b' directly to an unsigned 
int, and is compiled in 32 bits, and has the same endian-ness as the 
Python program, chances are the struct will work correctly, if you're 
running Python under the same conditions.


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


Re: real numbers with infinity precission

2009-11-20 Thread Steven D'Aprano
On Thu, 19 Nov 2009 09:50:44 +0100, Hans Larsen wrote:

 I have a READ.me file for real.py, but where could I get that module? I
 use Python 3.+
 
 I hope that sombody can help me

Have you googled for real.py?


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


Re: replacing numbers in LARGE MATRIX with criterium in 2 columns (a-- b)

2009-05-04 Thread Alessandro
On May 4, 2:38 pm, Alexzive zasaconsult...@gmail.com wrote:
 Hello,
 I have this matrix [20*4 - but it could be n*4 , with n~100,000] in
 file EL_list like this:

 1,  1,  2,  3
  2,  4,  1,  5
  3,  5,  1,  6
  4,  7,  5,  6
  5,  8,  7,  9
  6,  8,  5,  7
  7, 10,  9,  7
  8, 10, 11, 12
  9,  7, 13, 10
 10, 14, 15, 16
 11, 14, 17, 15
 12, 17, 14, 18
 13, 13, 16, 10
 14, 16, 15, 11
 15, 16, 11, 10
 16, 19, 20, 21
 17, 22, 15, 20
 18, 17, 20, 15
 19, 23, 20, 24
 20, 25, 24, 20

 I would like to replace some numbers in EL_list but only in columns
 2,3,4 using the criterium by line in file criterium (column 1 are
 the new numbers, column 2 the old ones).

 1   1
 2   3
 3   5
 4   12
 5   13
 6   14
 7   15
 8   16
 9   17
 10  18
 11  19
 12  10
 13  21
 14  22
 15  23
 16  24
 17  25




 For example all the 7 have to replaced by 15 and so on..


ERRATA: for example, all the 15 have to replaced by 7 and so on..
--
http://mail.python.org/mailman/listinfo/python-list


Re: Re: replacing numbers in LARGE MATRIX with criterium in 2 columns (a-- b)

2009-05-04 Thread Dave Angel



Alessandro wrote:

On May 4, 2:38 pm, Alexzive zasaconsult...@gmail.com wrote:
  

Hello,
I have this matrix [20*4 - but it could be n*4 , with n~100,000] in
file EL_list like this:

1,  1,  2,  3
 2,  4,  1,  5
 3,  5,  1,  6
 4,  7,  5,  6
 5,  8,  7,  9
 6,  8,  5,  7
 7, 10,  9,  7
 8, 10, 11, 12
 9,  7, 13, 10
10, 14, 15, 16
11, 14, 17, 15
12, 17, 14, 18
13, 13, 16, 10
14, 16, 15, 11
15, 16, 11, 10
16, 19, 20, 21
17, 22, 15, 20
18, 17, 20, 15
19, 23, 20, 24
20, 25, 24, 20

I would like to replace some numbers in EL_list but only in columns
2,3,4 using the criterium by line in file criterium (column 1 are
the new numbers, column 2 the old ones).

1   1
2   3
3   5
4   12
5   13
6   14
7   15
8   16
9   17
10  18
11  19
12  10
13  21
14  22
15  23
16  24
17  25





  

For example all the 7 have to replaced by 15 and so on..




ERRATA: for example, all the 15 have to replaced by 7 and so on..

  
What have you come up with so far?  Did the instructor give you any 
sample code to solve similar problems?  Did he really describe it as a 
matrix?


Sounds to me like you have two text files.  One contains a replacement 
table (which you can read into a dictionary), and the other (large) file 
is just text.  After building the dictionary, you'd want a loop that 
goes through the text file, splitting each line into a list of four.  
You then use the dictionary to replace list items 1, 2, and 3, and write 
the result someplace.


Try writing the code, see if anything goes wrong, and then ask for help.

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


Re: replacing numbers in LARGE MATRIX with criterium in 2 columns (a-- b)

2009-05-04 Thread MRAB

Alexzive wrote:

Hello,
I have this matrix [20*4 - but it could be n*4 , with n~100,000] in
file EL_list like this:

1,  1,  2,  3
 2,  4,  1,  5
 3,  5,  1,  6
 4,  7,  5,  6
 5,  8,  7,  9
 6,  8,  5,  7
 7, 10,  9,  7
 8, 10, 11, 12
 9,  7, 13, 10
10, 14, 15, 16
11, 14, 17, 15
12, 17, 14, 18
13, 13, 16, 10
14, 16, 15, 11
15, 16, 11, 10
16, 19, 20, 21
17, 22, 15, 20
18, 17, 20, 15
19, 23, 20, 24
20, 25, 24, 20

I would like to replace some numbers in EL_list but only in columns
2,3,4 using the criterium by line in file criterium (column 1 are
the new numbers, column 2 the old ones).

1   1
2   3
3   5
4   12
5   13
6   14
7   15
8   16
9   17
10  18
11  19
12  10
13  21
14  22
15  23
16  24
17  25

For example all the 7 have to replaced by 15 and so on..

-- How to implement it in a fast end efficient code?


Read the contents of criterium into a dict with the old value as the
key and the new value as the value and then iterate through the matrix
replacing the values in columns 2 to 4 with criterium.get(current_value,
current_value).

Incidentally, the singular of criteria is criterion because it's
Greek, not Latin.
--
http://mail.python.org/mailman/listinfo/python-list


Re: replacing numbers in LARGE MATRIX with criterium in 2 columns (a-- b)

2009-05-04 Thread Aahz
In article 68d22002-fc0a-4590-9395-c78b6ee41...@r34g2000vba.googlegroups.com,
Alexzive  zasaconsult...@gmail.com wrote:

I have this matrix [20*4 - but it could be n*4 , with n~100,000] in
file EL_list like this:

Take a look at NumPy
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

It is easier to optimize correct code than to correct optimized code.
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting numbers to words

2009-02-05 Thread Steve Holden
todp...@hotmail.com wrote:
 I've been trying to figure this out for over 2 hours and I'm really
 frustrated right now.
 
 I first made Python to ask user to input height in meters. If user puts
 certain value in meter, then it converts it to feet and inches as follows:
  
 
 Enter the height (in metres): 1.6
 
 It is 5 feet, 3 inches high.
  
  
 What I want to do is to make it type only words. For example, instead of
 its saying, It is 5 feet, 3 inches high, I want it to say, it is five
 feet, three inches high.
 I'd appreciate any suggestions.

Create a list or tuple of strings, and use the numbers to index the list.

lst = ['a', 'b', 'c']
ndx = 1
print The letter, lst[ndx], is number one

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Converting numbers to words

2009-02-05 Thread Brian Allen Vanderburg II

todp...@hotmail.com wrote:

 I've been trying to figure this out for over 2 hours and I'm really 
frustrated right now.


 I first made Python to ask user to input height in meters. If user 
puts certain value in meter, then it converts it to feet and inches as 
follows:
  


 Enter the height (in metres): 1.6

 It is 5 feet, 3 inches high.
  
  
 What I want to do is to make it type only words. For example, instead 
of its saying, It is 5 feet, 3 inches high, I want it to say, it is 
five feet, three inches high.

 I'd appreciate any suggestions.

I made something similar in the past.  First I break it into two 
functions, one function handles 0-999 and return '' for zero or a 
meaningful value for 999, another function handles how many groups there 
are and for each one, gets the value for it calls the first function, 
and appends the correct word.  This only works for the English language 
though


Brian Vanderburg II

num_words1 = (zero, # not used
one,
two,
three,
four,
five,
six,
seven,
eight,
nine,
ten,
eleven,
twelve,
thirteen,
fourteen,
fifteen,
sixteen,
seventeen,
eighteen,
nineteen)

num_words2 = (twenty,
thirty,
forty,
fifty,
sixty,
seventy,
eighty,
ninety)

num_words3 = (thousand,
million,
billion,
trillion,
quadrillion)

def word_func1(value):
  # value can be from 0 to 999
  result = ''

  if value == 0:
  return result

  # Handle hundreds
  if value = 100:
  hvalue = int(value / 100)
  if result:
  result += ' '
  result += num_words1[hvalue]
  result += ' hundred'
  value -= (hvalue * 100)

  if value == 0:
  return result

  # Handle 1-19
  if value  20:
  if result:
  result += ' '
  result += num_words1[value]
  return result

  # Handle 10s (20-90)
  tvalue = int(value / 10)
  if result:
  result += ' '
  result += num_words2[tvalue - 2]
  value -= (tvalue * 10)

  if value == 0:
  return result

  # Handle ones
  if result:
  result += ' '
  result += num_words1[value]

  return result

def word_func2(value):
  result = ''

  if value == 0:
  return 'zero'

  # Determine support values
  divider = 1
  l = len(num_words3)
  for i in range(l):
  divider *= 1000

  for i in range(l):
  if value = divider:
  dvalue = int(value / divider)
  if result:
  result += ' '
  result += word_func1(dvalue)
  result += ' '
  result += num_words3[l - i - 1]
  value -= (dvalue * divider)
  divider /= 1000

  if value  0:
  if result:
  result += ' '
  result += word_func1(value)

  return result

number_to_word = word_func2

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


Re: Idenfity numbers in variables

2008-10-20 Thread John Machin
On Oct 20, 10:16 pm, Alfons Nonell-Canals [EMAIL PROTECTED]
wrote:
 Hello,
 I have a trouble and I don't know how to solve it. I am working with
 molecules and each molecule has a number of atoms. I obtain each atom
 spliting the molecule.

 Ok. It is fine and I have no problem with it.

 The problem is when I have to work with these atoms. These atoms usually
 are only a letter but, sometimes it can also contain one o more numbers.
 If they contein a number I have to manipulate them separately.

 If the number was allways the same I know how to identify them, for
 example, 1:

 atom = 'C1'

 if '1' in atom:
         print 'kk'

 But, how can I do to identify in '1' all possibilities from 1-9, I
 tried:

 if '[1-9]', \d,...

 Any comments, please?

Sorry, I can't parse identify in '1' all possibilities from 1-9.

Please give examples of what a valid atom with more than one digit
looks like, and what is not valid e.g. 'C12' is valid, so is 'C21',
but 'C11' and 'C22' are not valid.

Then give examples (in words, not in pseudo-Python) of tests/queries
that should produce True, and examples that should produce False -- if
indeed the result is intended to be a Boolean; if not, you'd better
tell us what you want.

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


Re: Idenfity numbers in variables

2008-10-20 Thread Peter Otten
Alfons Nonell-Canals wrote:

 I have a trouble and I don't know how to solve it. I am working with
 molecules and each molecule has a number of atoms. I obtain each atom
 spliting the molecule.
 
 Ok. It is fine and I have no problem with it.
 
 The problem is when I have to work with these atoms. These atoms usually
 are only a letter but, sometimes it can also contain one o more numbers.
 If they contein a number I have to manipulate them separately.
 
 If the number was allways the same I know how to identify them, for
 example, 1:
 
 atom = 'C1'
 
 if '1' in atom:
 print 'kk'
 
 But, how can I do to identify in '1' all possibilities from 1-9, I
 tried:
 
 if '[1-9]', \d,...
 
 Any comments, please?

http://mail.python.org/pipermail/tutor/1999-March/83.html

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


Re: Idenfity numbers in variables

2008-10-20 Thread Tim Chase

atom = 'C1'

if '1' in atom:
print 'kk'

But, how can I do to identify in '1' all possibilities from 1-9, I
tried:

if '[1-9]', \d,...


You're reaching in the right direction (regexps), so just use 
Python's re module:


  import re
  digit = re.compile(r'\d') # or [0-9]
  for test in [C1, N98, CJ, 3.141, 43+5i, ]:
print test,
if digit.search(test):
  print has,
else:
  print doesn't have,
print a digit in it

The regexp can be tightened up if you want to ensure that it has 
a letter in front of it, or a number of other tests but that 
should be a decent start.


-tim


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


Re: Idenfity numbers in variables

2008-10-20 Thread Paul McGuire
On Oct 20, 7:07 am, Peter Otten [EMAIL PROTECTED] wrote:
 Alfons Nonell-Canals wrote:
  I have a trouble and I don't know how to solve it. I am working with
  molecules and each molecule has a number of atoms. I obtain each atom
  spliting the molecule.

  Ok. It is fine and I have no problem with it.

  The problem is when I have to work with these atoms. These atoms usually
  are only a letter but, sometimes it can also contain one o more numbers.
  If they contein a number I have to manipulate them separately.

  If the number was allways the same I know how to identify them, for
  example, 1:

  atom = 'C1'

  if '1' in atom:
  print 'kk'

  But, how can I do to identify in '1' all possibilities from 1-9, I
  tried:

  if '[1-9]', \d,...

  Any comments, please?

 http://mail.python.org/pipermail/tutor/1999-March/83.html

 Peter- Hide quoted text -

 - Show quoted text -

Wow, that sure is a lot of code.  And I'm not sure the OP wants to
delve into re's just to solve this problem.  Here is the pyparsing
rendition (although it does not handle the recursive computation of
submolecules given in parens, as the Tim Peters link above does):
http://pyparsing.wikispaces.com/file/view/chemicalFormulas.py

The pyparsing version defines chemical symbols and their coefficients
as using the following code:

caps = ABCDEFGHIJKLMNOPQRSTUVWXYZ
lowers = caps.lower()
digits = 0123456789

element = Word( caps, lowers )
integer = Word( digits )
elementRef = Group( element + Optional( integer, default=1 ) )
chemicalFormula = OneOrMore( elementRef )


Then to parse a formula like C6H5OH, there is no need to code up a
tokenizer, just call parseString:

elements = chemicalFormula.parseString(C6H5OH)

The URL above links to a better annotated example, included 2 more
extended versions that show how to use the resulting parsed data to
compute the molecular weight of the chemical.

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


Re: Idenfity numbers in variables

2008-10-20 Thread Lie Ryan
On Mon, 20 Oct 2008 13:16:48 +0200, Alfons Nonell-Canals wrote:

 Hello,
 I have a trouble and I don't know how to solve it. I am working with
 molecules and each molecule has a number of atoms. I obtain each atom
 spliting the molecule.
 
 Ok. It is fine and I have no problem with it.
 
 The problem is when I have to work with these atoms. These atoms usually
 are only a letter but, sometimes it can also contain one o more numbers.
 If they contein a number I have to manipulate them separately.
 
 If the number was allways the same I know how to identify them, for
 example, 1:
 
 atom = 'C1'
 
 if '1' in atom:
   print 'kk'
 
 But, how can I do to identify in '1' all possibilities from 1-9, I
 tried:
 
 if '[1-9]', \d,...
 

That's the job of regular expression: 'import re'

numbered_atom = re.compile('[A-Z][a-z]?[0-9]+')
if numbered_atom.match('C10'):
# this is a numbered atom
if numbered_atom.match('C'):
# this WON'T match

read more about regular expression on the web (hint: python share the 
same re syntax with many other languages, php, javascript, grep, etc)

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


Re: Idenfity numbers in variables

2008-10-20 Thread Duncan Booth
Lie Ryan [EMAIL PROTECTED] wrote:

 That's the job of regular expression: 'import re'
 
 numbered_atom = re.compile('[A-Z][a-z]?[0-9]+')
 if numbered_atom.match('C10'):
 # this is a numbered atom
 if numbered_atom.match('C'):
 # this WON'T match
 
 read more about regular expression on the web (hint: python share the 
 same re syntax with many other languages, php, javascript, grep, etc)
 

Or simply:

if atom[-1].isdigit():
   # this is a numbered atom
else:
   # this isn't
--
http://mail.python.org/mailman/listinfo/python-list


Re: replace numbers in a string

2008-10-09 Thread Gary Herron
Beema Shafreen wrote:
 hi All,

 i have few lines in file
 ttccatttctggacatgacgtctgt6901ggtttaagctttgtgaaagaatgtgctttgattcg
 i need to replace the number and get only the alphabet in such a case
 what should i do.
 Can any body suggest me
From the regular expression module, use re.sub like this:


 import re
 re.sub('[0-9]', '',
ttccatttctggacatgacgtctgt6901ggtttaagctttgtgaaagaatgtgctttgattcg)
'ttccatttctggacatgacgtctgtggtttaagctttgtgaaagaatgtgctttgattcg'


Gary Herron




 -- 
 Beema Shafreen
 

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

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


Re: replace numbers in a string

2008-10-09 Thread Peter Otten
Gary Herron wrote:

 Beema Shafreen wrote:
 hi All,

 i have few lines in file
 ttccatttctggacatgacgtctgt6901ggtttaagctttgtgaaagaatgtgctttgattcg
 i need to replace the number and get only the alphabet in such a case
 what should i do.
 Can any body suggest me
From the regular expression module, use re.sub like this:
 
 
 import re
 re.sub('[0-9]', '',
 ttccatttctggacatgacgtctgt6901ggtttaagctttgtgaaagaatgtgctttgattcg)
 'ttccatttctggacatgacgtctgtggtttaagctttgtgaaagaatgtgctttgattcg'

Or use str methods.
In Python 2.6:

 import string
 tctgt6901ggtttaa.translate(None, string.digits) 
'tctgtggtttaa'

Older versione:

 tctgt6901ggtttaa.translate(string.maketrans(, ), string.digits)
'tctgtggtttaa'

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


Re: negative numbers are not equal...

2008-08-15 Thread Fredrik Lundh

ariel ledesma wrote:

i see now, so i guess that's also why id() returns the same address for 
them as well...
i'll dive into the implementation file, it may be a bit out of my league 
but i'll see what i can gather, and hey, that's how it works, right? :-)


well, there's another strategy, of course: instead of spending time on 
figuring out when you can get away with doing things the wrong way on a 
specific version (and have your programs break when you upgrade), 
despite what the documentation says, you can spend that time writing 
new, portable code that works and does useful things.


/F

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


Re: negative numbers are not equal...

2008-08-15 Thread Steven D'Aprano
On Thu, 14 Aug 2008 20:44:32 -0700, castironpi wrote:

 For
 
 a= 6
 b= a
 
 the test
 
 a is b
 
 should clearly return true.

Since Python promises not to make a copy of a when you execute b = a, 
then I think that such behaviour is guaranteed by the language.


 Python distinguishes what mathematics does
 not, between identity and equality. Clearly 5+4 and 6+3 - evaluate- to
 the same, but math doesn't define whether they are the same, and in some
 sense the question isn't asked ordinarily, or isn't debated.  I want to
 infer that math doesn't define the 'is' relation as Python knows it.

Mathematicians often *define* equality as identity. That certainly makes 
sense when dealing with numbers -- what would it mean to say that there 
are (say) three different instances of the abstract integer 42, all equal 
yet not identical? I suggest that this simply doesn't make sense -- it is 
not even wrong.

Equality-as-identity may not hold in all areas of mathematics, but I 
think it is safe to say it holds for ideal (abstract) numbers, as opposed 
to implementations of numbers as bit patterns or objects in memory.

http://en.wikipedia.org/wiki/Equality_(mathematics)



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


Re: negative numbers are not equal...

2008-08-15 Thread Dan Lenski
On Thu, 14 Aug 2008 17:18:55 -0300, ariel ledesma wrote:

 hello guys
 
 i just ran into this when comparing negative numbers, they start
 returning False from -6 down, but only when comparing with 'is'
 
   m = -5
   a = -5
   m is a
 True
   m = -6
   a = -6
   m is a
 False
   m == a
 True
 
 i read that 'is' compares if they are really the same object, but i
 don't that's it because then why does -5 return True? of course i could
 only use == to compare, but still, what am i missing here? thanks in
 advance

They also return False for positive numbers  256.  Try this:
  print [x for x in range(-10,260) if x is not x+1-1]
[-10, -9, -8, -7, -6, 257, 258, 259]

There is a good explanation for this: the is operator checks for object 
identity, not equality.  Basically a is m asks, does the variable name 
a reference the same memory location as the variable name m?

For integers in the range of -5=x=256, Python pre-caches all of these 
values, and whenever a variable takes on one of those values, it uses the 
cached value.  This is an optimization: it prevents the need to allocate 
a new Python object for these very very common small integer values.

For integer literals outside this range, a new Python object gets created 
when they are assigned to variables, so a=500 followed by m=500 will 
create new objects.

The is operator just shows the effect of this caching.  It's 
unimportant for real code since you never care whether two numeric 
variables refer to the same object (only important for complex data 
structures where their storage may overlap)... only whether they are 
equal or not.

Dan Lenski

(PS- The small integer pre-caching is described somewhere in the C API 
docs.)

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


Re: negative numbers are not equal...

2008-08-15 Thread Carl Banks
On Aug 14, 4:42 pm, Christian Heimes [EMAIL PROTECTED] wrote:
 Integers
 between -5 and +256 are singletons as are some other objects like
 strings with one element or empty tuples.

Not quite.

Python 2.5.2 (r252:60911, May 28 2008, 08:35:32)
[GCC 4.2.4 (Debian 4.2.4-1)] on linux2
Type help, copyright, credits or license for more information.
 a = 'A'
 b = %c % a
 a
'A'
 b
'A'
 a is b
False


 You must not rely on the
 optimization.

Good advice.


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


Re: negative numbers are not equal...

2008-08-15 Thread castironpi
On Aug 15, 8:56 am, Dan Lenski [EMAIL PROTECTED] wrote:
 On Thu, 14 Aug 2008 17:18:55 -0300, ariel ledesma wrote:
  hello guys

  i just ran into this when comparing negative numbers, they start
  returning False from -6 down, but only when comparing with 'is'

    m = -5
    a = -5
    m is a
  True
    m = -6
    a = -6
    m is a
  False
    m == a
  True

  i read that 'is' compares if they are really the same object, but i
  don't that's it because then why does -5 return True? of course i could
  only use == to compare, but still, what am i missing here? thanks in
  advance

 They also return False for positive numbers  256.  Try this:
   print [x for x in range(-10,260) if x is not x+1-1]
 [-10, -9, -8, -7, -6, 257, 258, 259]

 There is a good explanation for this: the is operator checks for object
 identity, not equality.  Basically a is m asks, does the variable name
 a reference the same memory location as the variable name m?

 For integers in the range of -5=x=256, Python pre-caches all of these
 values, and whenever a variable takes on one of those values, it uses the
 cached value.  This is an optimization: it prevents the need to allocate
 a new Python object for these very very common small integer values.

 For integer literals outside this range, a new Python object gets created
 when they are assigned to variables, so a=500 followed by m=500 will
 create new objects.

 The is operator just shows the effect of this caching.  It's
 unimportant for real code since you never care whether two numeric
 variables refer to the same object (only important for complex data
 structures where their storage may overlap)... only whether they are
 equal or not.

 Dan Lenski

 (PS- The small integer pre-caching is described somewhere in the C API
 docs.)

It would be nice to put together a really canonical case of the use of
the 'is' comparison.  FTSOA for the sake of argument, when do you use
it?  Why is it even in the language?

If you're iterating over a list,

flagA= object()
flagB= object()
flagC= -10
listA= [ objectA, objectB, flagA, objectC, flagB, -10, objectD ]
flags= [ listA, listB, listC ]
for iA in listA:
   for flag in flags:
  if iA is flag:
 handle( iA )

This case actually misses handleC().  The solution is that the
function that is returning '-10' cannot return -10, it has to return
flagC.  This can cause difficulties in cases when you're doing
operations on flags.  Worse, if flagC is nested somewhere, say
moduleA.classB.flagC, you still have to work with that, not its value.
--
http://mail.python.org/mailman/listinfo/python-list


Re: negative numbers are not equal...

2008-08-15 Thread Bruno Desthuilliers

castironpi a écrit :
(snip)

It would be nice to put together a really canonical case of the use of
the 'is' comparison.  FTSOA for the sake of argument, when do you use
it? 


When I want to test objects identity. An idenity test is an identity 
test is an identity test is an



Why is it even in the language?


Because there's a need for it.

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


Re: negative numbers are not equal...

2008-08-15 Thread Fredrik Lundh

castironpi wrote:


This case actually misses handleC().  The solution is that the
function that is returning '-10' cannot return -10, it has to return
flagC.  This can cause difficulties in cases when you're doing
operations on flags.  Worse, if flagC is nested somewhere, say
moduleA.classB.flagC, you still have to work with that, not its value.


do you *ever* make any sense at all?

/F

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


  1   2   3   4   >