Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread Thomas Passin via Python-list

On 5/29/2024 10:59 AM, MRAB via Python-list wrote:

On 2024-05-29 15:32, Thomas Passin via Python-list wrote:

On 5/29/2024 8:55 AM, Kevin M. Wilson wrote:
Please recall, I said the format for the email failed to retain the 
proper indents.

I'll attach a picture of the code!
Purpose; to uppercase every other letter in a string.

Thanks all, KMW


Simpler is good, and readability is good.  For a simple conversion that
has a little touch of generality:

s1 = 'this is a test'
def convert(i, ch):
  return ch.upper() if i % 2 else ch

result = ''.join([convert(i, ch) for i, ch in enumerate(s1)])
print(result)  # tHiS Is a tEsT


[snip]
Small mistake there. The original code converted to uppercase on even 
indexes, whereas your code does it on odd ones.


I wondered if anyone would catch that :)  Anyway, I don't think the 
original question was whether to start with even or odd but ways to 
iterate character by character and do something, right?



However, this has a weakness: what to do about spaces.  Should they be
counted among the characters to be uppercased? or should they not be
included in the count of the alternation?  If you want to uppercase
every other letter that is not a space, things become a little more
complicated.  And then do you want this to apply to all whitespace or
only spaces?

If you want to skip changing spaces, then you need to track the state of
converted characters in some way.  It would probably be easier (and more
readable) to use a "for x in t:" construction:


Actually, I did mess up the action for a space.  It should be:

def convert(convert_this, ch):
"""Convert character ch if convert_this is True.
Don't convert spaces.
"""
if ch == ' ':
   return (convert_this, ch)
if convert_this:
   return (False, ch.upper())
return (True, ch)

We should never get two printable uppercased characters in a row, even 
if there is a space between them, but my original convert(convert_this, 
ch) did.



def convert(convert_this, ch):
  """Convert character ch if convert_this is True.
  Don't convert spaces.
  """
  if convert_this:
  if ch == ' ':
  return (convert_this, ch)
  elif convert_this:
  return (False, ch.upper())
  return (True, ch)

convert_next = False
result = ''
for ch in s1:
  convert_next, ch = convert(convert_next, ch)
  result += ch
print(result)  # tHiS Is A TeSt

There could be even more complications if you allow non-ascii characters
but you were asking about processing character by character so I won't
get into that.

(You haven't specified the problem in enough detail to answer questions
like those).


[snip]




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


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread Grant Edwards via Python-list
On 2024-05-29, Mats Wichmann via Python-list  wrote:
> On 5/29/24 08:02, Grant Edwards via Python-list wrote:
>> On 2024-05-29, Chris Angelico via Python-list  wrote:
>> 
>>> print(f"if block {name[index]=} {index=}")
>> 
>> Holy cow!  How did I not know about the f-string {=} thing?
>
> It's more recent than f-strings in general, so it's not that hard to miss.

I really should make a habit of reading through the "what's new" pages
when new releases come out...

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


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread MRAB via Python-list

On 2024-05-29 15:32, Thomas Passin via Python-list wrote:

On 5/29/2024 8:55 AM, Kevin M. Wilson wrote:
Please recall, I said the format for the email failed to retain the 
proper indents.

I'll attach a picture of the code!
Purpose; to uppercase every other letter in a string.

Thanks all, KMW


Simpler is good, and readability is good.  For a simple conversion that
has a little touch of generality:

s1 = 'this is a test'
def convert(i, ch):
  return ch.upper() if i % 2 else ch

result = ''.join([convert(i, ch) for i, ch in enumerate(s1)])
print(result)  # tHiS Is a tEsT


[snip]
Small mistake there. The original code converted to uppercase on even 
indexes, whereas your code does it on odd ones.



However, this has a weakness: what to do about spaces.  Should they be
counted among the characters to be uppercased? or should they not be
included in the count of the alternation?  If you want to uppercase
every other letter that is not a space, things become a little more
complicated.  And then do you want this to apply to all whitespace or
only spaces?

If you want to skip changing spaces, then you need to track the state of
converted characters in some way.  It would probably be easier (and more
readable) to use a "for x in t:" construction:

def convert(convert_this, ch):
  """Convert character ch if convert_this is True.
  Don't convert spaces.
  """
  if convert_this:
  if ch == ' ':
  return (convert_this, ch)
  elif convert_this:
  return (False, ch.upper())
  return (True, ch)

convert_next = False
result = ''
for ch in s1:
  convert_next, ch = convert(convert_next, ch)
  result += ch
print(result)  # tHiS Is A TeSt

There could be even more complications if you allow non-ascii characters
but you were asking about processing character by character so I won't
get into that.

(You haven't specified the problem in enough detail to answer questions
like those).


[snip]


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


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread Barry Scott via Python-list



> On 29 May 2024, at 05:38, Kevin M. Wilson via Python-list 
>  wrote:
> 
> The format in this email is not of my making, should someone know, how to do 
> this so that it's a readable script do tell!
> KMW


Your mail program may have a plain-text mode to compose messages in try using 
that.

Barry

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


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread Thomas Passin via Python-list

On 5/29/2024 8:55 AM, Kevin M. Wilson wrote:
Please recall, I said the format for the email failed to retain the 
proper indents.

I'll attach a picture of the code!
Purpose; to uppercase every other letter in a string.

Thanks all, KMW


Simpler is good, and readability is good.  For a simple conversion that 
has a little touch of generality:


s1 = 'this is a test'
def convert(i, ch):
return ch.upper() if i % 2 else ch

result = ''.join([convert(i, ch) for i, ch in enumerate(s1)])
print(result)  # tHiS Is a tEsT

However, this has a weakness: what to do about spaces.  Should they be 
counted among the characters to be uppercased? or should they not be 
included in the count of the alternation?  If you want to uppercase 
every other letter that is not a space, things become a little more 
complicated.  And then do you want this to apply to all whitespace or 
only spaces?


If you want to skip changing spaces, then you need to track the state of 
converted characters in some way.  It would probably be easier (and more 
readable) to use a "for x in t:" construction:


def convert(convert_this, ch):
"""Convert character ch if convert_this is True.
Don't convert spaces.
"""
if convert_this:
if ch == ' ':
return (convert_this, ch)
elif convert_this:
return (False, ch.upper())
return (True, ch)

convert_next = False
result = ''
for ch in s1:
convert_next, ch = convert(convert_next, ch)
result += ch
print(result)  # tHiS Is A TeSt

There could be even more complications if you allow non-ascii characters 
but you were asking about processing character by character so I won't 
get into that.


(You haven't specified the problem in enough detail to answer questions 
like those).





***
"When you pass through the waters, I will be with you: and when you pass 
through the rivers, they will not sweep over you. When you walk through 
the fire, you will not be burned: the flames will not set you ablaze."

*Isaiah 43:2
*


On Wednesday, May 29, 2024 at 06:19:56 AM MDT, Thomas Passin via 
Python-list  wrote:



On 5/29/2024 3:14 AM, Chris Angelico via Python-list wrote:
 > On Wed, 29 May 2024 at 16:03, Cameron Simpson via Python-list
 > mailto:python-list@python.org>> wrote:
 >> By which Thomas means stuff like this:
 >>
 >>      print(f'if block {name[index]} and index {index}')
 >>
 >> Notice the leading "f'". Personally I wouldn't even go that far, just:
 >>
 >>      print('if block', name[index], 'and index', index)
 >>
 >> But there are plenty of places where f-strings are very useful.
 >
 > I wouldn't replace str.format() everywhere, nor would I replace
 > percent encoding everywhere - but in this case, I think Thomas is
 > correct. Not because it's 2024 (f-strings were brought in back in
 > 2015, so they're hardly chronologically special),

I only meant that they have been around for 9 years and are usually more
readable, so just change over already.  I had some inertia over them
myself (imagine sticking with % formatting!) so I understand.


 > but because most of
 > this looks like debugging output that can take advantage of this
 > feature:
 >
 > print(f"if block {name[index]=} {index=}")
 >
 > ChrisA

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



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


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread Mats Wichmann via Python-list

On 5/29/24 08:02, Grant Edwards via Python-list wrote:

On 2024-05-29, Chris Angelico via Python-list  wrote:


print(f"if block {name[index]=} {index=}")


Holy cow!  How did I not know about the f-string {=} thing?



It's more recent than f-strings in general, so it's not that hard to miss.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread Grant Edwards via Python-list
On 2024-05-29, Chris Angelico via Python-list  wrote:

> print(f"if block {name[index]=} {index=}")

Holy cow!  How did I not know about the f-string {=} thing?

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


Re: Formatted Output and Argument Parsing (was: Re: Flubbed it in the second interation through the string: range error... HOW?)

2024-05-29 Thread Chris Angelico via Python-list
On Wed, 29 May 2024 at 23:06, Dan Sommers via Python-list
 wrote:
> (For the history-impaired, getopt existed long before Python and will
> likely exist long after it, but getopt's "replacement" optparse lasted
> only from 2003 until 2011.)

Depends on your definition of "lasted". It's not getting developed
further, but it's still there. If you started using it, you're welcome
to keep going.

https://docs.python.org/3/library/optparse.html

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


Formatted Output and Argument Parsing (was: Re: Flubbed it in the second interation through the string: range error... HOW?)

2024-05-29 Thread Dan Sommers via Python-list
On 2024-05-29 at 17:14:51 +1000,
Chris Angelico via Python-list  wrote:

> I wouldn't replace str.format() everywhere, nor would I replace
> percent encoding everywhere - but in this case, I think Thomas is
> correct. Not because it's 2024 (f-strings were brought in back in
> 2015, so they're hardly chronologically special), but because most of
> this looks like debugging output that can take advantage of this
> feature:
> 
> print(f"if block {name[index]=} {index=}")

defsnark:

After years of getopt (and even more, if you include non-Python
experience), I'm glad I decided to wait a decade before chugging the
optparse koolaid.

(For the history-impaired, getopt existed long before Python and will
likely exist long after it, but getopt's "replacement" optparse lasted
only from 2003 until 2011.)

That said, I agree that the = thing makes f-strings eminently useful for
debugging, and I wholeheartedly agree with not fixing things that aren't
broken.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread Thomas Passin via Python-list

On 5/29/2024 3:14 AM, Chris Angelico via Python-list wrote:

On Wed, 29 May 2024 at 16:03, Cameron Simpson via Python-list
 wrote:

By which Thomas means stuff like this:

  print(f'if block {name[index]} and index {index}')

Notice the leading "f'". Personally I wouldn't even go that far, just:

  print('if block', name[index], 'and index', index)

But there are plenty of places where f-strings are very useful.


I wouldn't replace str.format() everywhere, nor would I replace
percent encoding everywhere - but in this case, I think Thomas is
correct. Not because it's 2024 (f-strings were brought in back in
2015, so they're hardly chronologically special),


I only meant that they have been around for 9 years and are usually more 
readable, so just change over already.  I had some inertia over them 
myself (imagine sticking with % formatting!) so I understand.



but because most of
this looks like debugging output that can take advantage of this
feature:

print(f"if block {name[index]=} {index=}")

ChrisA


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


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread MRAB via Python-list

On 2024-05-29 05:33, Kevin M. Wilson via Python-list wrote:

The following is my effort to understand how to process a string, letter, by 
letter:
def myfunc(name):        index = 0    howmax = len(name)    # while (index <= 
howmax):    while (index < howmax):        if (index % 2 == 0):            
print('letter to upper = {}, index {}!'.format(name[index], index))            name = 
name[index].upper()            print('if block {} and index {}'.format(name[index], 
index))        elif (index % 2 > 0):            print(index)            print('Start: 
elseif block, index is {}, letter is {}'.format(index, name))            # print('letter 
to lower = {}'.format(name[index]))            # print('Already lowercase do noting: 
name = {}'.format(name[index]))        index += 1        # index = name.upper()
     return name
myfunc('capitalism')
Error message:                        Not making sense, index is 1, letter s/b 
'a'letter to upper = c, index 0!
if block C and index 0
1
Start: elseif block, index is 1, letter is C
---
IndexErrorTraceback (most recent call last)
Cell In[27], line 21
  17 # index = name.upper()
  19 return name
---> 21 myfunc('capitalism')

Cell In[27], line 8, in myfunc(name)
   6 while (index < howmax):
   7 if (index % 2 == 0):
> 8 print('letter to upper = {}, index {}!'.format(name[index], 
index))
   9 name = name[index].upper()
  10 print('if block {} and index {}'.format(name[index], index))

IndexError: string index out of 
range***
So, I'm doing something... Stupid!!
***
"When you pass through the waters, I will be with you: and when you pass through the 
rivers, they will not sweep over you. When you walk through the fire, you will not be 
burned: the flames will not set you ablaze."
Isaiah 43:2


I think the code is this:

def myfunc(name):
index = 0
howmax = len(name)
# while (index <= howmax):
while (index < howmax):
if (index % 2 == 0):
print('letter to upper = {}, index {}!'.format(name[index], 
index))

name = name[index].upper()
print('if block {} and index {}'.format(name[index], index))
elif (index % 2 > 0):
print(index)
print('Start: elseif block, index is {}, letter is 
{}'.format(index, name))

# print('letter to lower = {}'.format(name[index]))
# print('Already lowercase do noting: name = 
{}'.format(name[index]))

index += 1
# index = name.upper()
return name

myfunc('capitalism')


What is:

name = name[index].upper()

meant to be doing?

What it's _actually_ doing is getting the character at a given index, 
converting it to uppercase, and then assigning it to `name`, so `name` 
is now 1 character long.


It doesn't this when 'index' is 0, so after the first iteration, `name` 
is a single-character string.


On the second iteration it raises IndexError because the string is only 
1 character long and you're asking for `name[1]`.


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


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread Chris Angelico via Python-list
On Wed, 29 May 2024 at 16:03, Cameron Simpson via Python-list
 wrote:
> By which Thomas means stuff like this:
>
>  print(f'if block {name[index]} and index {index}')
>
> Notice the leading "f'". Personally I wouldn't even go that far, just:
>
>  print('if block', name[index], 'and index', index)
>
> But there are plenty of places where f-strings are very useful.

I wouldn't replace str.format() everywhere, nor would I replace
percent encoding everywhere - but in this case, I think Thomas is
correct. Not because it's 2024 (f-strings were brought in back in
2015, so they're hardly chronologically special), but because most of
this looks like debugging output that can take advantage of this
feature:

print(f"if block {name[index]=} {index=}")

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


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-28 Thread Cameron Simpson via Python-list

On 29May2024 01:14, Thomas Passin  wrote:
Also, it's 2024 ... time to start using f-strings (because they are 
more readable than str.format())


By which Thomas means stuff like this:

print(f'if block {name[index]} and index {index}')

Notice the leading "f'". Personally I wouldn't even go that far, just:

print('if block', name[index], 'and index', index)

But there are plenty of places where f-strings are very useful.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-28 Thread Thomas Passin via Python-list
Your code is unreadable. The lines have all run together.  And after 
that, kindly explain what you want your code sample to do.  "Process" 
doesn't say much.


From what I can make out about what you are trying to do, you would do 
better to index through your string with


for i, chr in enumerate(name):
# do something with the character

Also, it's 2024 ... time to start using f-strings (because they are more 
readable than str.format())


On 5/29/2024 12:33 AM, Kevin M. Wilson via Python-list wrote:

The following is my effort to understand how to process a string, letter, by 
letter:
def myfunc(name):        index = 0    howmax = len(name)    # while (index <= 
howmax):    while (index < howmax):        if (index % 2 == 0):            
print('letter to upper = {}, index {}!'.format(name[index], index))            name = 
name[index].upper()            print('if block {} and index {}'.format(name[index], 
index))        elif (index % 2 > 0):            print(index)            print('Start: 
elseif block, index is {}, letter is {}'.format(index, name))            # print('letter 
to lower = {}'.format(name[index]))            # print('Already lowercase do noting: 
name = {}'.format(name[index]))        index += 1        # index = name.upper()
     return name
myfunc('capitalism')
Error message:                        Not making sense, index is 1, letter s/b 
'a'letter to upper = c, index 0!
if block C and index 0
1
Start: elseif block, index is 1, letter is C
---
IndexErrorTraceback (most recent call last)
Cell In[27], line 21
  17 # index = name.upper()
  19 return name
---> 21 myfunc('capitalism')

Cell In[27], line 8, in myfunc(name)
   6 while (index < howmax):
   7 if (index % 2 == 0):
> 8 print('letter to upper = {}, index {}!'.format(name[index], 
index))
   9 name = name[index].upper()
  10 print('if block {} and index {}'.format(name[index], index))

IndexError: string index out of 
range***
So, I'm doing something... Stupid!!
***
"When you pass through the waters, I will be with you: and when you pass through the 
rivers, they will not sweep over you. When you walk through the fire, you will not be 
burned: the flames will not set you ablaze."
Isaiah 43:2


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


Fw: Flubbed it in the second interation through the string: range error... HOW?

2024-05-28 Thread Kevin M. Wilson via Python-list
The format in this email is not of my making, should someone know, how to do 
this so that it's a readable script do tell!
KMW

***
"When you pass through the waters, I will be with you: and when you pass 
through the rivers, they will not sweep over you. When you walk through the 
fire, you will not be burned: the flames will not set you ablaze."      
Isaiah 43:2
 

   - Forwarded Message - From: Kevin M. Wilson via Python-list 
To: python-list@python.org 
Sent: Tuesday, May 28, 2024 at 10:35:23 PM MDTSubject: 
Flubbed it in the second interation through the string: range error... HOW?
 The following is my effort to understand how to process a string, letter, by 
letter:
def myfunc(name):        index = 0    howmax = len(name)    # while (index <= 
howmax):    while (index < howmax):        if (index % 2 == 0):            
print('letter to upper = {}, index {}!'.format(name[index], index))            
name = name[index].upper()            print('if block {} and index 
{}'.format(name[index], index))        elif (index % 2 > 0):            
print(index)            print('Start: elseif block, index is {}, letter is 
{}'.format(index, name))            # print('letter to lower = 
{}'.format(name[index]))            # print('Already lowercase do noting: name 
= {}'.format(name[index]))        index += 1        # index = name.upper()      
  
    return name        
myfunc('capitalism')
Error message:                        Not making sense, index is 1, letter s/b 
'a'letter to upper = c, index 0!
if block C and index 0
1
Start: elseif block, index is 1, letter is C
---
IndexError                                Traceback (most recent call last)
Cell In[27], line 21
    17        # index = name.upper()        
    19    return name        
---> 21 myfunc('capitalism')

Cell In[27], line 8, in myfunc(name)
      6 while (index < howmax):
      7    if (index % 2 == 0):
> 8        print('letter to upper = {}, index {}!'.format(name[index], 
index))
      9        name = name[index].upper()
    10        print('if block {} and index {}'.format(name[index], index))

IndexError: string index out of 
range***
So, I'm doing something... Stupid!!
***
"When you pass through the waters, I will be with you: and when you pass 
through the rivers, they will not sweep over you. When you walk through the 
fire, you will not be burned: the flames will not set you ablaze."      
Isaiah 43:2
-- 
https://mail.python.org/mailman/listinfo/python-list
  
-- 
https://mail.python.org/mailman/listinfo/python-list


Flubbed it in the second interation through the string: range error... HOW?

2024-05-28 Thread Kevin M. Wilson via Python-list
The following is my effort to understand how to process a string, letter, by 
letter:
def myfunc(name):        index = 0    howmax = len(name)    # while (index <= 
howmax):    while (index < howmax):        if (index % 2 == 0):            
print('letter to upper = {}, index {}!'.format(name[index], index))            
name = name[index].upper()            print('if block {} and index 
{}'.format(name[index], index))        elif (index % 2 > 0):            
print(index)            print('Start: elseif block, index is {}, letter is 
{}'.format(index, name))            # print('letter to lower = 
{}'.format(name[index]))            # print('Already lowercase do noting: name 
= {}'.format(name[index]))        index += 1        # index = name.upper()      
  
    return name        
myfunc('capitalism')
Error message:                        Not making sense, index is 1, letter s/b 
'a'letter to upper = c, index 0!
if block C and index 0
1
Start: elseif block, index is 1, letter is C
---
IndexErrorTraceback (most recent call last)
Cell In[27], line 21
 17 # index = name.upper()
 19 return name
---> 21 myfunc('capitalism')

Cell In[27], line 8, in myfunc(name)
  6 while (index < howmax):
  7 if (index % 2 == 0):
> 8 print('letter to upper = {}, index {}!'.format(name[index], 
index))
  9 name = name[index].upper()
     10 print('if block {} and index {}'.format(name[index], index))

IndexError: string index out of 
range***
So, I'm doing something... Stupid!!
***
"When you pass through the waters, I will be with you: and when you pass 
through the rivers, they will not sweep over you. When you walk through the 
fire, you will not be burned: the flames will not set you ablaze."      
Isaiah 43:2
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 2.7 range Function provokes a Memory Error

2023-03-06 Thread Chris Angelico
On Tue, 7 Mar 2023 at 16:53, Stephen Tucker  wrote:
>
> Hi again,
>
> I tried xrange, but I got an error telling me that my integer was too big
> for a C long.
>
> Clearly, xrange in Py2 is not capable of dealing with Python (that is,
> possibly very long) integers.

That's because Py2 has two different integer types, int and long.

> I am raising this because,
>
> (a) IF xrange in Py3 is a simple "port" from Py2, then it won't handle
> Python integers either.
>
> AND
>
> (b) IF xrange in Py3 is intended to be equivalent to range (which, even in
> Py2, does handle Python integers)
>
> THEN
>
> It could be argued that xrange in Py3 needs some attention from the
> developer(s).


Why don't you actually try Python 3 instead of making assumptions
based on the state of Python from more than a decade ago?

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


Re: Python 2.7 range Function provokes a Memory Error

2023-03-06 Thread Stephen Tucker
Hi again,

I tried xrange, but I got an error telling me that my integer was too big
for a C long.

Clearly, xrange in Py2 is not capable of dealing with Python (that is,
possibly very long) integers.

I am raising this because,

(a) IF xrange in Py3 is a simple "port" from Py2, then it won't handle
Python integers either.

AND

(b) IF xrange in Py3 is intended to be equivalent to range (which, even in
Py2, does handle Python integers)

THEN

It could be argued that xrange in Py3 needs some attention from the
developer(s).

Stephen Tucker.


On Thu, Mar 2, 2023 at 6:24 PM Jon Ribbens via Python-list <
python-list@python.org> wrote:

> On 2023-03-02, Stephen Tucker  wrote:
> > The range function in Python 2.7 (and yes, I know that it is now
> > superseded), provokes a Memory Error when asked to deiliver a very long
> > list of values.
> >
> > I assume that this is because the function produces a list which it then
> > iterates through.
> >
> > 1. Does the  range  function in Python 3.x behave the same way?
>
> No, in Python 3 it is an iterator which produces the next number in the
> sequence each time.
>
> > 2. Is there any equivalent way that behaves more like a  for loop (that
> is,
> > without producing a list)?
>
> Yes, 'xrange' in Python 2 behaves like 'range' in Python 3.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 2.7 range Function provokes a Memory Error

2023-03-02 Thread Jon Ribbens via Python-list
On 2023-03-02, Stephen Tucker  wrote:
> The range function in Python 2.7 (and yes, I know that it is now
> superseded), provokes a Memory Error when asked to deiliver a very long
> list of values.
>
> I assume that this is because the function produces a list which it then
> iterates through.
>
> 1. Does the  range  function in Python 3.x behave the same way?

No, in Python 3 it is an iterator which produces the next number in the
sequence each time.

> 2. Is there any equivalent way that behaves more like a  for loop (that is,
> without producing a list)?

Yes, 'xrange' in Python 2 behaves like 'range' in Python 3.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 2.7 range Function provokes a Memory Error

2023-03-02 Thread Chris Angelico
On Thu, 2 Mar 2023 at 22:27, Stephen Tucker  wrote:
>
> Hi,
>
> The range function in Python 2.7 (and yes, I know that it is now
> superseded), provokes a Memory Error when asked to deiliver a very long
> list of values.
>
> I assume that this is because the function produces a list which it then
> iterates through.
>
> 1. Does the  range  function in Python 3.x behave the same way?

No, but list(range(x)) might, for the same reason. In Py2, range
returns a list, which means it needs a gigantic collection of integer
objects. In Py3, a range object just defines its start/stop/step, but
if you call list() on it, you get the same sort of

> 2. Is there any equivalent way that behaves more like a  for loop (that is,
> without producing a list)?
>
> To get round the problem I have written my own software that is used in a
> for  loop.

xrange is an iterator in Py2, so that's the easiest way to handle it.
Obviously migrating to Py3 would be the best way, but in the meantime,
xrange will probably do what you need.

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


Re: Python 2.7 range Function provokes a Memory Error

2023-03-02 Thread 2QdxY4RzWzUUiLuE
On 2023-03-02 at 11:25:49 +,
Stephen Tucker  wrote:

> The range function in Python 2.7 (and yes, I know that it is now
> superseded), provokes a Memory Error when asked to deiliver a very long
> list of values.
> 
> I assume that this is because the function produces a list which it then
> iterates through.
> 
> 1. Does the  range  function in Python 3.x behave the same way?

No.

> 2. Is there any equivalent way that behaves more like a  for loop (that is,
> without producing a list)?

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


Python 2.7 range Function provokes a Memory Error

2023-03-02 Thread Stephen Tucker
Hi,

The range function in Python 2.7 (and yes, I know that it is now
superseded), provokes a Memory Error when asked to deiliver a very long
list of values.

I assume that this is because the function produces a list which it then
iterates through.

1. Does the  range  function in Python 3.x behave the same way?

2. Is there any equivalent way that behaves more like a  for loop (that is,
without producing a list)?

To get round the problem I have written my own software that is used in a
for  loop.

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


Re: Comparing sequences with range objects

2022-04-11 Thread Antoon Pardon




Op 11/04/2022 om 02:31 schreef Dan Stromberg:


It sounds a little like you're looking for interval arithmetic.

Maybe https://pypi.org/project/python-intervals/1.5.3/ ?


Not completely but it suggested an idea to explore.

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


Re: Comparing sequences with range objects

2022-04-11 Thread Antoon Pardon



Op 11/04/2022 om 02:01 schreef duncan smith:

On 10/04/2022 21:20, Antoon Pardon wrote:



Op 9/04/2022 om 02:01 schreef duncan smith:

On 08/04/2022 22:08, Antoon Pardon wrote:


Well my first thought is that a bitset makes it less obvious to 
calulate

the size of the set or to iterate over its elements. But it is an idea
worth exploring.





def popcount(n):
    """
    Returns the number of set bits in n
    """
    cnt = 0
    while n:
    n &= n - 1
    cnt += 1
    return cnt

and not tested,

def iterinds(n):
    """
    Returns a generator of the indices of the set bits of n
    """
    i = 0
    while n:
    if n & 1:
    yield i
    n = n >> 1
    i += 1

Sure but these seem rather naive implementation with a time 
complexity of
O(n) where n is the maximum number of possible elements. Using these 
would

turn my O(n) algorithm in a O(n^2) algorithm.



I thought your main concern was memory. Of course, dependent on 
various factors, you might be able to do much better than the above. 
But I don't know what your O(n) algorithm is, how using a bitset would 
make it O(n^2), or if the O(n^2) algorithm would actually be slower 
for typical n. The overall thing sounds broadly like some of the 
blocking and clustering methods I've come across in record linkage.


Using bitsets would make change my algorithm from O(n) into O(n^2) because
the bitset operations are O(n) instead of O(1). If I have a 2 people
a bitset will take a vector of about 300, 64bit words. With 4 people
the bitset will take a vector of about 600. So doubling the population
will also double the time for the bitset operations, meaning doubling
the population will increase execution time four times.

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


Re: Comparing sequences with range objects

2022-04-10 Thread Dan Stromberg
Two more things:
1) There are also modules that do interval arithmetic with reals, not just
integers.  EG: https://pyinterval.readthedocs.io/en/latest/
2) If you don't mind a small amount of inaccuracy you can often get things
down to less than one bit per element for presence/absence, using a bloom
filter.  EG: https://pypi.org/project/drs-bloom-filter/

On Sun, Apr 10, 2022 at 5:31 PM Dan Stromberg  wrote:

>
> It sounds a little like you're looking for interval arithmetic.
>
> Maybe https://pypi.org/project/python-intervals/1.5.3/ ?
>
> On Thu, Apr 7, 2022 at 4:19 AM Antoon Pardon  wrote:
>
>> I am working with a list of data from which I have to weed out duplicates.
>> At the moment I keep for each entry a container with the other entries
>> that are still possible duplicates.
>>
>> The problem is sometimes that is all the rest. I thought to use a range
>> object for these cases. Unfortunatly I sometimes want to sort things
>> and a range object is not comparable with a list or a tuple.
>>
>> So I have a list of items where each item is itself a list or range
>> object.
>> I of course could sort this by using list as a key function but that
>> would defeat the purpose of using range objects for these cases.
>>
>> So what would be a relatively easy way to get the same result without
>> wasting
>> too much memory on entries that haven't any weeding done on them.
>>
>> --
>> Antoon Pardon.
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Comparing sequences with range objects

2022-04-10 Thread 2QdxY4RzWzUUiLuE
On 2022-04-10 at 22:20:33 +0200,
Antoon Pardon  wrote:

> 
> 
> Op 9/04/2022 om 02:01 schreef duncan smith:
> > On 08/04/2022 22:08, Antoon Pardon wrote:
> > > 
> > > Well my first thought is that a bitset makes it less obvious to calulate
> > > the size of the set or to iterate over its elements. But it is an idea
> > > worth exploring.
> > > 
> > 
> > 
> > 
> > def popcount(n):
> >     """
> >     Returns the number of set bits in n
> >     """
> >     cnt = 0
> >     while n:
> >     n &= n - 1
> >     cnt += 1
> >     return cnt
> > 
> > and not tested,
> > 
> > def iterinds(n):
> >     """
> >     Returns a generator of the indices of the set bits of n
> >     """
> >     i = 0
> >     while n:
> >     if n & 1:
> >     yield i
> >     n = n >> 1
> >     i += 1
> > 
> Sure but these seem rather naive implementation with a time complexity of
> O(n) where n is the maximum number of possible elements. Using these would
> turn my O(n) algorithm in a O(n^2) algorithm.

O(n) where n is the expected number of elements.  The loops iterate once
for each bit actually contained in the set, which is usually [much] less
than the size of the universe.  If you have lots and lots of elements in
your sets, or your universe is large and n is a long integer, then these
may not be as efficient as other methods.  You know your data better
than we do.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Comparing sequences with range objects

2022-04-10 Thread Dan Stromberg
It sounds a little like you're looking for interval arithmetic.

Maybe https://pypi.org/project/python-intervals/1.5.3/ ?

On Thu, Apr 7, 2022 at 4:19 AM Antoon Pardon  wrote:

> I am working with a list of data from which I have to weed out duplicates.
> At the moment I keep for each entry a container with the other entries
> that are still possible duplicates.
>
> The problem is sometimes that is all the rest. I thought to use a range
> object for these cases. Unfortunatly I sometimes want to sort things
> and a range object is not comparable with a list or a tuple.
>
> So I have a list of items where each item is itself a list or range object.
> I of course could sort this by using list as a key function but that
> would defeat the purpose of using range objects for these cases.
>
> So what would be a relatively easy way to get the same result without
> wasting
> too much memory on entries that haven't any weeding done on them.
>
> --
> Antoon Pardon.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Comparing sequences with range objects

2022-04-10 Thread duncan smith

On 10/04/2022 21:20, Antoon Pardon wrote:



Op 9/04/2022 om 02:01 schreef duncan smith:

On 08/04/2022 22:08, Antoon Pardon wrote:


Well my first thought is that a bitset makes it less obvious to calulate
the size of the set or to iterate over its elements. But it is an idea
worth exploring.





def popcount(n):
    """
    Returns the number of set bits in n
    """
    cnt = 0
    while n:
    n &= n - 1
    cnt += 1
    return cnt

and not tested,

def iterinds(n):
    """
    Returns a generator of the indices of the set bits of n
    """
    i = 0
    while n:
    if n & 1:
    yield i
    n = n >> 1
    i += 1


Sure but these seem rather naive implementation with a time complexity of
O(n) where n is the maximum number of possible elements. Using these would
turn my O(n) algorithm in a O(n^2) algorithm.



I thought your main concern was memory. Of course, dependent on various 
factors, you might be able to do much better than the above. But I don't 
know what your O(n) algorithm is, how using a bitset would make it 
O(n^2), or if the O(n^2) algorithm would actually be slower for typical 
n. The overall thing sounds broadly like some of the blocking and 
clustering methods I've come across in record linkage.


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


Re: Comparing sequences with range objects

2022-04-10 Thread Antoon Pardon



Op 9/04/2022 om 02:01 schreef duncan smith:

On 08/04/2022 22:08, Antoon Pardon wrote:


Well my first thought is that a bitset makes it less obvious to calulate
the size of the set or to iterate over its elements. But it is an idea
worth exploring.





def popcount(n):
    """
    Returns the number of set bits in n
    """
    cnt = 0
    while n:
    n &= n - 1
    cnt += 1
    return cnt

and not tested,

def iterinds(n):
    """
    Returns a generator of the indices of the set bits of n
    """
    i = 0
    while n:
    if n & 1:
    yield i
    n = n >> 1
    i += 1


Sure but these seem rather naive implementation with a time complexity of
O(n) where n is the maximum number of possible elements. Using these would
turn my O(n) algorithm in a O(n^2) algorithm.

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


Re: Comparing sequences with range objects

2022-04-09 Thread Ian Hobson



On 09/04/2022 13:14, Christian Gollwitzer wrote:

Am 08.04.22 um 09:21 schrieb Antoon Pardon:

The first is really hard. Not only may information be missing, no single
single piece of information is unique or immutable. Two people may have
the same name (I know about several other "Peter Holzer"s), a single
person might change their name (when I was younger I went by my middle
name - how would you know that "Peter Holzer" and "Hansi Holzer" are the
same person?), they will move (= change their address), change jobs,
etc. Unless you have a unique immutable identifier that's enforced by
some authority (like a social security number[1]), I don't think there
is a chance to do that reliably in a program (although with enough data,
a heuristic may be good enough).


Yes I know all that. That is why I keep a bucket of possible duplicates
per "identifying" field that is examined and use some heuristics at the
end of all the comparing instead of starting to weed out the duplicates
at the moment something differs.

The problem is, that when an identifying field is judged to be unusable,
the bucket to be associated with it should conceptually contain all other
records (which in this case are the indexes into the population list).
But that will eat a lot of memory. So I want some object that behaves as
if it is a (immutable) list of all these indexes without actually 
containing

them. A range object almost works, with the only problem it is not
comparable with a list.



Then write your own comparator function?

Also, if the only case where this actually works is the index of all 
other records, then a simple boolean flag "all" vs. "these items in the 
index list" would suffice - doesn't it?


 Christian

Writing a comparator function is only possible for a given key. So my 
approach would be:


1) Write a comparator function that takes params X and Y, such that:
if key data is missing from X, return 1
If key data is missing from Y return -1
if X > Y return 1
if X < Y return -1
return 0 # They are equal and key data for both is present

2) Sort the data using the comparator function.

3) Run through the data with a trailing enumeration loop, merging 
matching records together.


4) If there are no records copied out with missing
key data, then you are done, so exit.

5) Choose a new key and repeat from step 1).

Regards

Ian

--
Ian Hobson
Tel (+66) 626 544 695

--
This email has been checked for viruses by AVG.
https://www.avg.com

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


Re: Comparing sequences with range objects

2022-04-09 Thread Christian Gollwitzer

Am 08.04.22 um 09:21 schrieb Antoon Pardon:

The first is really hard. Not only may information be missing, no single
single piece of information is unique or immutable. Two people may have
the same name (I know about several other "Peter Holzer"s), a single
person might change their name (when I was younger I went by my middle
name - how would you know that "Peter Holzer" and "Hansi Holzer" are the
same person?), they will move (= change their address), change jobs,
etc. Unless you have a unique immutable identifier that's enforced by
some authority (like a social security number[1]), I don't think there
is a chance to do that reliably in a program (although with enough data,
a heuristic may be good enough).


Yes I know all that. That is why I keep a bucket of possible duplicates
per "identifying" field that is examined and use some heuristics at the
end of all the comparing instead of starting to weed out the duplicates
at the moment something differs.

The problem is, that when an identifying field is judged to be unusable,
the bucket to be associated with it should conceptually contain all other
records (which in this case are the indexes into the population list).
But that will eat a lot of memory. So I want some object that behaves as
if it is a (immutable) list of all these indexes without actually 
containing

them. A range object almost works, with the only problem it is not
comparable with a list.



Then write your own comparator function?

Also, if the only case where this actually works is the index of all 
other records, then a simple boolean flag "all" vs. "these items in the 
index list" would suffice - doesn't it?


Christian

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


Re: Comparing sequences with range objects

2022-04-09 Thread duncan smith

On 08/04/2022 22:08, Antoon Pardon wrote:


Op 8/04/2022 om 16:28 schreef duncan smith:

On 08/04/2022 08:21, Antoon Pardon wrote:


Yes I know all that. That is why I keep a bucket of possible duplicates
per "identifying" field that is examined and use some heuristics at the
end of all the comparing instead of starting to weed out the duplicates
at the moment something differs.

The problem is, that when an identifying field is judged to be unusable,
the bucket to be associated with it should conceptually contain all 
other

records (which in this case are the indexes into the population list).
But that will eat a lot of memory. So I want some object that behaves as
if it is a (immutable) list of all these indexes without actually 
containing

them. A range object almost works, with the only problem it is not
comparable with a list.



Is there any reason why you can't use ints? Just set the relevant bits.


Well my first thought is that a bitset makes it less obvious to calulate
the size of the set or to iterate over its elements. But it is an idea
worth exploring.





def popcount(n):
"""
Returns the number of set bits in n
"""
cnt = 0
while n:
n &= n - 1
cnt += 1
return cnt

and not tested,

def iterinds(n):
"""
Returns a generator of the indices of the set bits of n
"""
i = 0
while n:
if n & 1:
yield i
n = n >> 1
i += 1


Duncan


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


Re: Comparing sequences with range objects

2022-04-08 Thread Antoon Pardon



Op 8/04/2022 om 16:28 schreef duncan smith:

On 08/04/2022 08:21, Antoon Pardon wrote:


Yes I know all that. That is why I keep a bucket of possible duplicates
per "identifying" field that is examined and use some heuristics at the
end of all the comparing instead of starting to weed out the duplicates
at the moment something differs.

The problem is, that when an identifying field is judged to be unusable,
the bucket to be associated with it should conceptually contain all 
other

records (which in this case are the indexes into the population list).
But that will eat a lot of memory. So I want some object that behaves as
if it is a (immutable) list of all these indexes without actually 
containing

them. A range object almost works, with the only problem it is not
comparable with a list.



Is there any reason why you can't use ints? Just set the relevant bits.


Well my first thought is that a bitset makes it less obvious to calulate
the size of the set or to iterate over its elements. But it is an idea
worth exploring.

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


Re: Comparing sequences with range objects

2022-04-08 Thread duncan smith

On 08/04/2022 08:21, Antoon Pardon wrote:



Op 8/04/2022 om 08:24 schreef Peter J. Holzer:

On 2022-04-07 17:16:41 +0200, Antoon Pardon wrote:

Op 7/04/2022 om 16:08 schreef Joel Goldstick:
On Thu, Apr 7, 2022 at 7:19 AM Antoon Pardon   
wrote:
I am working with a list of data from which I have to weed out 
duplicates.

At the moment I keep for each entry a container with the other entries
that are still possible duplicates.

[...]
Sorry I wasn't clear. The data contains information about persons. 
But not

all records need to be complete. So a person can occur multiple times in
the list, while the records are all different because they are missing
different bits.

So all records with the same firstname can be duplicates. But if I have
a record in which the firstname is missing, it can at that point be
a duplicate of all other records.

There are two problems. The first one is how do you establish identity.
The second is how do you ween out identical objects. In your first mail
you only asked about the second, but that's easy.

The first is really hard. Not only may information be missing, no single
single piece of information is unique or immutable. Two people may have
the same name (I know about several other "Peter Holzer"s), a single
person might change their name (when I was younger I went by my middle
name - how would you know that "Peter Holzer" and "Hansi Holzer" are the
same person?), they will move (= change their address), change jobs,
etc. Unless you have a unique immutable identifier that's enforced by
some authority (like a social security number[1]), I don't think there
is a chance to do that reliably in a program (although with enough data,
a heuristic may be good enough).


Yes I know all that. That is why I keep a bucket of possible duplicates
per "identifying" field that is examined and use some heuristics at the
end of all the comparing instead of starting to weed out the duplicates
at the moment something differs.

The problem is, that when an identifying field is judged to be unusable,
the bucket to be associated with it should conceptually contain all other
records (which in this case are the indexes into the population list).
But that will eat a lot of memory. So I want some object that behaves as
if it is a (immutable) list of all these indexes without actually 
containing

them. A range object almost works, with the only problem it is not
comparable with a list.



Is there any reason why you can't use ints? Just set the relevant bits.

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


Re: Comparing sequences with range objects

2022-04-08 Thread Antoon Pardon




Op 8/04/2022 om 08:24 schreef Peter J. Holzer:

On 2022-04-07 17:16:41 +0200, Antoon Pardon wrote:

Op 7/04/2022 om 16:08 schreef Joel Goldstick:

On Thu, Apr 7, 2022 at 7:19 AM Antoon Pardon   wrote:

I am working with a list of data from which I have to weed out duplicates.
At the moment I keep for each entry a container with the other entries
that are still possible duplicates.

[...]

Sorry I wasn't clear. The data contains information about persons. But not
all records need to be complete. So a person can occur multiple times in
the list, while the records are all different because they are missing
different bits.

So all records with the same firstname can be duplicates. But if I have
a record in which the firstname is missing, it can at that point be
a duplicate of all other records.

There are two problems. The first one is how do you establish identity.
The second is how do you ween out identical objects. In your first mail
you only asked about the second, but that's easy.

The first is really hard. Not only may information be missing, no single
single piece of information is unique or immutable. Two people may have
the same name (I know about several other "Peter Holzer"s), a single
person might change their name (when I was younger I went by my middle
name - how would you know that "Peter Holzer" and "Hansi Holzer" are the
same person?), they will move (= change their address), change jobs,
etc. Unless you have a unique immutable identifier that's enforced by
some authority (like a social security number[1]), I don't think there
is a chance to do that reliably in a program (although with enough data,
a heuristic may be good enough).


Yes I know all that. That is why I keep a bucket of possible duplicates
per "identifying" field that is examined and use some heuristics at the
end of all the comparing instead of starting to weed out the duplicates
at the moment something differs.

The problem is, that when an identifying field is judged to be unusable,
the bucket to be associated with it should conceptually contain all other
records (which in this case are the indexes into the population list).
But that will eat a lot of memory. So I want some object that behaves as
if it is a (immutable) list of all these indexes without actually containing
them. A range object almost works, with the only problem it is not
comparable with a list.

--
Antoon Pardon.

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


Re: Comparing sequences with range objects

2022-04-07 Thread Chris Angelico
On Fri, 8 Apr 2022 at 16:26, Peter J. Holzer  wrote:
> Unless you have a unique immutable identifier that's enforced by
> some authority (like a social security number[1]), I don't think there
> is a chance to do that reliably in a program (although with enough data,
> a heuristic may be good enough).
>

Not sure what your footnote was supposed to be, but I'll offer two
useful footnotes to that:

[1] [a] Though they're not actually immutable either, just less
frequently changing

[1[ [b] Of course, that has privacy implications.

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


Re: Comparing sequences with range objects

2022-04-07 Thread Peter J. Holzer
On 2022-04-07 17:16:41 +0200, Antoon Pardon wrote:
> Op 7/04/2022 om 16:08 schreef Joel Goldstick:
> > On Thu, Apr 7, 2022 at 7:19 AM Antoon Pardon  wrote:
> > > I am working with a list of data from which I have to weed out duplicates.
> > > At the moment I keep for each entry a container with the other entries
> > > that are still possible duplicates.
[...]
> Sorry I wasn't clear. The data contains information about persons. But not
> all records need to be complete. So a person can occur multiple times in
> the list, while the records are all different because they are missing
> different bits.
> 
> So all records with the same firstname can be duplicates. But if I have
> a record in which the firstname is missing, it can at that point be
> a duplicate of all other records.

There are two problems. The first one is how do you establish identity.
The second is how do you ween out identical objects. In your first mail
you only asked about the second, but that's easy.

The first is really hard. Not only may information be missing, no single
single piece of information is unique or immutable. Two people may have
the same name (I know about several other "Peter Holzer"s), a single
person might change their name (when I was younger I went by my middle
name - how would you know that "Peter Holzer" and "Hansi Holzer" are the
same person?), they will move (= change their address), change jobs,
etc. Unless you have a unique immutable identifier that's enforced by
some authority (like a social security number[1]), I don't think there
is a chance to do that reliably in a program (although with enough data,
a heuristic may be good enough).

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Comparing sequences with range objects

2022-04-07 Thread MRAB

On 2022-04-07 16:16, Antoon Pardon wrote:

Op 7/04/2022 om 16:08 schreef Joel Goldstick:

On Thu, Apr 7, 2022 at 7:19 AM Antoon Pardon  wrote:

I am working with a list of data from which I have to weed out duplicates.
At the moment I keep for each entry a container with the other entries
that are still possible duplicates.

The problem is sometimes that is all the rest. I thought to use a range
object for these cases. Unfortunatly I sometimes want to sort things
and a range object is not comparable with a list or a tuple.

So I have a list of items where each item is itself a list or range object.
I of course could sort this by using list as a key function but that
would defeat the purpose of using range objects for these cases.

So what would be a relatively easy way to get the same result without wasting
too much memory on entries that haven't any weeding done on them.

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

I'm not sure I understand what you are trying to do, but if your data
has no order, you can use set to remove the duplicates


Sorry I wasn't clear. The data contains information about persons. But not
all records need to be complete. So a person can occur multiple times in
the list, while the records are all different because they are missing
different bits.

So all records with the same firstname can be duplicates. But if I have
a record in which the firstname is missing, it can at that point be
a duplicate of all other records.


This is how I'd approach it:

# Make a list of groups, where each group is a list of potential duplicates.
# Initially, all of the records are potential duplicates of each other.
records = [list_of_records]

# Split the groups into subgroups according to the first name.
new_records = []

for group in records:
subgroups = defaultdict(list)

for record in group:
subgroups[record['first_name']].append(record)

# Records without a first name could belong to any of the subgroups.
missing = subgroups.pop(None, [])

for record in missing:
for subgroup in subgroups.values():
subgroup.extend(missing)

new_records.extend(subgroups.values())

records = new_records

# Now repeat for the last name, etc.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Comparing sequences with range objects

2022-04-07 Thread Dieter Maurer
Antoon Pardon wrote at 2022-4-7 17:16 +0200:
> ...
>Sorry I wasn't clear. The data contains information about persons. But not
>all records need to be complete. So a person can occur multiple times in
>the list, while the records are all different because they are missing
>different bits.
>
>So all records with the same firstname can be duplicates. But if I have
>a record in which the firstname is missing, it can at that point be
>a duplicate of all other records.

The description is still not clear enough. Especially, it does
not show where `range` objects come into play.


Answering on a more abstract level:
Apparently, you want to sort a list the elements of which can
be other lists or range objects.

List objects are ordered lexicographically, i.e. for lists l1, l2:
l1 <= l2 iff not l1 or (l2 and l1[0] <= l2[0] and l1[1:] <= l2[1:]).
If you want to sort a list containing list elements are compared using
this order.

For your case, you would need to use a `key` parameter for `sort` that
implements this order for `range` objects, too.
(Note that Python provides a function which transforms an order
definition into an appropriate `key` function).
A corresponding `sort` call may expand your range objects completely.

An alternative might be to not expand `range` objects but to put them
all at the start or end of the sorted list.
Of course, this would imply that their expansion does not influence
their order in the list -- which may or may not be acceptable
(depending on your use case).
If it is acceptable, it is likely possible to not put range objects
into the list to be sorted in the first place.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Comparing sequences with range objects

2022-04-07 Thread Antoon Pardon

Op 7/04/2022 om 16:08 schreef Joel Goldstick:

On Thu, Apr 7, 2022 at 7:19 AM Antoon Pardon  wrote:

I am working with a list of data from which I have to weed out duplicates.
At the moment I keep for each entry a container with the other entries
that are still possible duplicates.

The problem is sometimes that is all the rest. I thought to use a range
object for these cases. Unfortunatly I sometimes want to sort things
and a range object is not comparable with a list or a tuple.

So I have a list of items where each item is itself a list or range object.
I of course could sort this by using list as a key function but that
would defeat the purpose of using range objects for these cases.

So what would be a relatively easy way to get the same result without wasting
too much memory on entries that haven't any weeding done on them.

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

I'm not sure I understand what you are trying to do, but if your data
has no order, you can use set to remove the duplicates


Sorry I wasn't clear. The data contains information about persons. But not
all records need to be complete. So a person can occur multiple times in
the list, while the records are all different because they are missing
different bits.

So all records with the same firstname can be duplicates. But if I have
a record in which the firstname is missing, it can at that point be
a duplicate of all other records.

--
Antoon Pardon

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


Re: Comparing sequences with range objects

2022-04-07 Thread Joel Goldstick
On Thu, Apr 7, 2022 at 7:19 AM Antoon Pardon  wrote:
>
> I am working with a list of data from which I have to weed out duplicates.
> At the moment I keep for each entry a container with the other entries
> that are still possible duplicates.
>
> The problem is sometimes that is all the rest. I thought to use a range
> object for these cases. Unfortunatly I sometimes want to sort things
> and a range object is not comparable with a list or a tuple.
>
> So I have a list of items where each item is itself a list or range object.
> I of course could sort this by using list as a key function but that
> would defeat the purpose of using range objects for these cases.
>
> So what would be a relatively easy way to get the same result without wasting
> too much memory on entries that haven't any weeding done on them.
>
> --
> Antoon Pardon.
> --
> https://mail.python.org/mailman/listinfo/python-list

I'm not sure I understand what you are trying to do, but if your data
has no order, you can use set to remove the duplicates

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


Comparing sequences with range objects

2022-04-07 Thread Antoon Pardon

I am working with a list of data from which I have to weed out duplicates.
At the moment I keep for each entry a container with the other entries
that are still possible duplicates.

The problem is sometimes that is all the rest. I thought to use a range
object for these cases. Unfortunatly I sometimes want to sort things
and a range object is not comparable with a list or a tuple.

So I have a list of items where each item is itself a list or range object.
I of course could sort this by using list as a key function but that
would defeat the purpose of using range objects for these cases.

So what would be a relatively easy way to get the same result without wasting
too much memory on entries that haven't any weeding done on them.

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


Re: To check if number is in range(x,y)

2020-12-14 Thread Tim Chase
On 2020-12-14 21:21, Schachner, Joseph wrote:
> >>> r = range(10)  
> So r is a list containing 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

In Python 3.x, r is *not* a list.  It is a custom object/class.

>   >>> 2 in r  
>   True
> As expected.

I'm not sure what your replies are suggesting here.  I demonstrated
the OP's edge-cases, especially cases that one might experience coming
from other languages.

>   >>> r = range(1, 10, 2)
>   >>> 2 in r  
>   False
>   >>> list(r)  
>   [1, 3, 5, 7, 9]
> Well, yes, because you started the range at 1.  Start at 0 and
> you'd get 0, 2, 4, 6, 8.

Had I done this, for pedagogical value I would have checked for 3
then:

  >>> r = range(0, 10, 2)
  >>> 3 in r
  False

The goal was to demonstrate that the resulting range object, when
given a step-size of something than the default 1, will have holes in
it, and as such, testing for membership in one of those holes would
fail.  Showing successful membership wouldn't add any value.

> "It also doesn't automatically convert from the string inputs
> you're getting from the input() function:
> 
>   >>> s = "5"
>   >>> s in r  
>   False
>   >>> int(s) in r  
>   True"
> You have just discovered that Python, although it is dynamically
> typed, is STRICTLY typed. 

No, not just now discovered something I've long known.  The goal was
to provide an example for the OP of this exact case since their
original code attempted to use the string returned from input() and
used it as-is (without converting to int) for this exact sort of
comparison.

> Another way to say this: you have discovered that Python isn't the
> same as BASIC.

Additionally, (many? all? some?) BASICs have similarly strict typing.
For example, reaching for the BASIC that I used in the 80s:

  ] S$ = "HELLO"
  ] I = 42
  ] PRINT S$ + I
  ?TYPE MISMATCH ERROR

> "Additionally, note that the endpoint of the range is exclusive so
>   >>> r = range(1, 10)
>   >>> 10 in r  
>   False"
> 
> I don't have to note that

My comment was directed at the OP.  Unless you are Bischoop, that's
not you.

> Now suppose that the end integer was not excluded. Each range call
> would produce 11 integers. 

The goal was to show the OP that while some languages (such as the
aforementioned BASIC) have *inclusive* ranges:
  
  ] FOR I = 1 to 3 : PRINT I : NEXT
  1
  2
  3

Python's ranges are exclusive.  Because a language could have either,
the example demonstrated Python's choice.

> I recommend you read Python 101 and when you've done that, read
> Python 201.   I think they are very good "learn Python" books. If
> you're surprised that the end point is not included in range, you
> need to read Python 101.

Your condescending replies bark up the wrong tree.

-tkc






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


Re: To check if number is in range(x,y)

2020-12-14 Thread Dan Stromberg
On Mon, Dec 14, 2020 at 3:07 PM Dan Stromberg  wrote:

>
> On Mon, Dec 14, 2020 at 1:23 PM Schachner, Joseph <
> joseph.schach...@teledyne.com> wrote:
>
>> >>> r = range(10)
>> So r is a list containing 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
>>
> To get a list of consecutive int's, you can use, for EG:
> r = list(range(10))
>

Oh, and range() returning a (lazy) range is a new thing.  In Python 2.x,
range returned a list and you had to use xrange to get laziness.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To check if number is in range(x,y)

2020-12-14 Thread Dan Stromberg
On Mon, Dec 14, 2020 at 1:23 PM Schachner, Joseph <
joseph.schach...@teledyne.com> wrote:

> >>> r = range(10)
> So r is a list containing 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
>
To get a list of consecutive int's, you can use, for EG:
r = list(range(10))
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To check if number is in range(x,y)

2020-12-14 Thread 2QdxY4RzWzUUiLuE
On 2020-12-14 at 21:21:43 +,
"Schachner, Joseph"  wrote:

> >>> r = range(10)
> So r is a list containing 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

In a number of ways, r behaves as if it were that list, but r is
definitely not that list:

>>> r = range(10)
>>> type(r)

>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> type(l)

>>> r == l
False

> You have just discovered that Python, although it is dynamically
> typed, is STRICTLY typed.  Another way to say this: you have
> discovered that Python isn't the same as BASIC ...

Citation needed?  I can't speak for every version of BASIC ever, but the
ones I used had separate namespaces for numeric variables and string
variables:  A was a number, A$ was a string, and never the twain shall
meet.  That's strict typing.
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: To check if number is in range(x,y)

2020-12-14 Thread Schachner, Joseph
>>> r = range(10)
So r is a list containing 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

  >>> 2 in r
  True
As expected.

  >>> 2.5 in r
  False
Also as expected.  If you did int(floor(2.5)) in 5 that would be true.

  >>> r = range(1, 10, 2)
  >>> 2 in r
  False
  >>> list(r)
  [1, 3, 5, 7, 9]
Well, yes, because you started the range at 1.  Start at 0 and you'd get 0, 2, 
4, 6, 8.

"It also doesn't automatically convert from the string inputs you're getting 
from the input() function:

  >>> s = "5"
  >>> s in r
  False
  >>> int(s) in r
  True"
You have just discovered that Python, although it is dynamically typed, is 
STRICTLY typed.  Another way to say this: you have discovered that Python isn't 
the same as BASIC.  Yes, you have to convert strings to int or float, Python 
does not assume you want to if you did not do it. Similarly, you have to do 
something to convert int or float to text.  Python makes it very simple, but 
you have to do it.


"Additionally, note that the endpoint of the range is exclusive so
  >>> r = range(1, 10)
  >>> 10 in r
  False"

I don't have to note that, I KNOW that (as I've demonstrated above), because I 
read a couple of books on Python.  Python range starts on the number you 
specify and does NOT include the end number.
So: range(0,10) is 0 to 9(note that this is 10 integers)
  range(10,20) is 10 to 19(also 10 integers)
  range(20,30) is 20 to 29   (another 10 integers)

Now suppose that the end integer was not excluded. Each range call would 
produce 11 integers.  10, 20, and 30 would occur twice.  Or you'd have to set 
the range limits differently.

I recommend you read Python 101 and when you've done that, read Python 201.   I 
think they are very good "learn Python" books.
If you're surprised that the end point is not included in range, you need to 
read Python 101.

--- Joseph S.



-Original Message-
From: Tim Chase 
Sent: Saturday, December 12, 2020 11:51 AM
To: Bischoop 
Cc: Bischoop ; python-list@python.org
Subject: Re: To check if number is in range(x,y)

On 2020-12-12 15:12, Bischoop wrote:
> I need to check if input number is 1-5. Whatever I try it's not
> working. Here are my aproaches to the problem: https://bpa.st/H62A
>
> What I'm doing wrong and how I should do it?

A range is similar to a list in that it contains just the numbers
listed:

  >>> r = range(10)
  >>> 2 in r
  True
  >>> 2.5 in r
  False
  >>> r = range(1, 10, 2)
  >>> 2 in r
  False
  >>> list(r)
  [1, 3, 5, 7, 9]

It also doesn't automatically convert from the string inputs you're getting 
from the input() function:

  >>> s = "5"
  >>> s in r
  False
  >>> int(s) in r
  True

Additionally, note that the endpoint of the range is exclusive so

  >>> r = range(1, 10)
  >>> 10 in r
  False
  >>> list(r)
  [1, 2, 3, 4, 5, 6, 7, 8, 9]

If you want numeric-range checks, Python provides the lovely double-comparison 
syntax:

  >>> x = 5
  >>> 2 < x < 10
  True
  >>> x = 5.5
  >>> 2 < x < 10
  True
  >>> s = "5"
  >>> 2 < s < 10
  Traceback…
  >>> 2 < int(s) < 10
  True

Hopefully this gives you the hints that you need to troubleshoot.

-tkc






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


Re: To check if number is in range(x,y)

2020-12-12 Thread Bischoop
On 2020-12-12, Tim Chase  wrote:
>
> Hopefully this gives you the hints that you need to troubleshoot.
>
> -tkc
>
>
>
>

Yes it explains a lot.

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


Re: To check if number is in range(x,y)

2020-12-12 Thread 2QdxY4RzWzUUiLuE
On 2020-12-12 at 10:51:00 -0600,
Tim Chase  wrote:

> If you want numeric-range checks, Python provides the lovely
> double-comparison syntax:
> 
>   >>> x = 5
>   >>> 2 < x < 10
>   True

Not just numbers:

>>> 'm' < 'n' < 'o'
True

>>> 'one' < 'one point five' < 'two'
True

Okay, so the second one is a trap, but you get the idea.  ;-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To check if number is in range(x,y)

2020-12-12 Thread Tim Chase
On 2020-12-12 15:12, Bischoop wrote:
> I need to check if input number is 1-5. Whatever I try it's not
> working. Here are my aproaches to the problem: https://bpa.st/H62A
> 
> What I'm doing wrong and how I should do it?

A range is similar to a list in that it contains just the numbers
listed:

  >>> r = range(10)
  >>> 2 in r
  True
  >>> 2.5 in r
  False
  >>> r = range(1, 10, 2)
  >>> 2 in r
  False
  >>> list(r)
  [1, 3, 5, 7, 9]

It also doesn't automatically convert from the string inputs you're
getting from the input() function:

  >>> s = "5"
  >>> s in r
  False
  >>> int(s) in r
  True

Additionally, note that the endpoint of the range is exclusive so

  >>> r = range(1, 10)
  >>> 10 in r
  False
  >>> list(r)
  [1, 2, 3, 4, 5, 6, 7, 8, 9]

If you want numeric-range checks, Python provides the lovely
double-comparison syntax:

  >>> x = 5
  >>> 2 < x < 10
  True
  >>> x = 5.5
  >>> 2 < x < 10
  True
  >>> s = "5"
  >>> 2 < s < 10
  Traceback…
  >>> 2 < int(s) < 10
  True

Hopefully this gives you the hints that you need to troubleshoot.

-tkc




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


Re: To check if number is in range(x,y)

2020-12-12 Thread Bischoop


Got it solved here: https://bpa.st/BFJA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To check if number is in range(x,y)

2020-12-12 Thread Oscar
In article ,
Bischoop   wrote:
>
>I need to check if input number is 1-5. Whatever I try it's not working.
>Here are my aproaches to the problem: https://bpa.st/H62A
>
>What I'm doing wrong and how I should do it?

You need to learn about types. ;-)

Input returns a string. That string is not in the range you compare it
to. You need to convert it to an int:

choice = int(input.. )

This is assuming you want a whole number. You compare it against the
list of numbers [1, 2, 3, 4, 5]. If 2.4 is also a valid number, you need
a different comparison. 2.4 is not in this list. 

So first you should get your requirements straight.. ;-)
-- 
[J|O|R] <- .signature.gz
-- 
https://mail.python.org/mailman/listinfo/python-list


To check if number is in range(x,y)

2020-12-12 Thread Bischoop


I need to check if input number is 1-5. Whatever I try it's not working.
Here are my aproaches to the problem: https://bpa.st/H62A

What I'm doing wrong and how I should do it?

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


Re: To check if number is in range(x,y)

2020-12-12 Thread Bischoop


I've also convert the choice to int() but doesn't help.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To check if number is in range(x,y)

2020-12-12 Thread Bischoop
On 2020-12-12, Oscar  wrote:
> In article ,
> Bischoop   wrote:
>>I've also convert the choice to int() but doesn't help.
>
> Oh.. did not read this yet. How did you do this? In both places after
> the input or during the comparison? If so, in which version? Only the
> first version would work. The other two are just plain wrong.

after the input, https://bpa.st/BFJA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: To check if number is in range(x,y)

2020-12-12 Thread Oscar
In article ,
Bischoop   wrote:
>I've also convert the choice to int() but doesn't help.

Oh.. did not read this yet. How did you do this? In both places after
the input or during the comparison? If so, in which version? Only the
first version would work. The other two are just plain wrong.
-- 
[J|O|R] <- .signature.gz
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: About float/double type number in range.

2020-08-26 Thread Rob Cliffe via Python-list




On 26/08/2020 12:02, Peter J. Holzer wrote:

On 2020-08-26 22:40:36 +1200, dn via Python-list wrote:

On 26/08/2020 19:58, Joel Goldstick wrote:


[...]

<<< Code NB Python v3.8 >>>
def fp_range( start:float, stop:float, step:float=1.0 )->float:
     """Generate a range of floating-point numbers."""
 if stop <= start:
 raise OverflowError( "RangeError: start must be less than stop" )
 x = start
 while x < stop:
 yield x
 x += step

This is almost the same solution as I came up with, but note that this
is not quote the same as what Joel proposed. Repeated addition is not
the same as multiplication with floating point numbers.
To expand on this: it is because floating point numbers cannot represent 
all real numbers exactly.
Repeated addition of a number represented inexactly will drift away from 
the mathematical value.
Example: fp_range(0, 70, 0.07) as written above will yield 1001 numbers 
ending with 69.66 (i.e. approximately, but not quite, 70).
Whereas Peter's version (below) will correctly yield 1000 numbers ending 
with 69.93.
(Even then some numbers are not represented exactly, e.g. the 
last-but-one is 69.860001.)


  


A generator based on Joel's idea would look like this:

def fp_range(start, end, step):
     v = start
 n = int(math.ceil((end - start) / step))
 for i in range(n):
 yield start + i * step



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


Re: About float/double type number in range.

2020-08-26 Thread Terry Reedy

On 8/26/2020 6:40 AM, dn via Python-list wrote:

def fp_range( start:float, stop:float, step:float=1.0 )->float:
     """Generate a range of floating-point numbers."""
     if stop <= start:
     raise OverflowError( "RangeError: start must be less than stop" )
     x = start
     while x < stop:
     yield x
     x += step


This only works exactly as expected for fraction steps of k/2**n give 
exactly.  Your only tests used .5 and .25.


print(list(fp_range(0.0, 2.01, .1)))
produces
[0.0, 0.1, 0.2, 0.30004, 0.4, 0.5, 0.6, 0.7, 
0.7999, 0.8999, 0., 
1.0999, 1.2, 1.3, 1.4001, 1.5002, 
1.6003, 1.7004, 1.8005, 
1.9006, 2.0004]


For exact fractional steps, one should use fractions or multiply and 
divide by the denominator, as shown by Joel, after stepping by the 
numerator.



--
Terry Jan Reedy


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


Re: About float/double type number in range.

2020-08-26 Thread Richard Damon
On 8/25/20 10:39 PM, ADITYA wrote:
>Dear Sir/Ma’am
>
>I am requesting you to satisfy me about float number in Range function,
>because in the argument of range we can take integer but not double or
>float whenever double as well as float are integer in nature but when we
>use double/float in, it gives error that- “'float' object cannot be
>interpreted as an integer.” If we want to increment the number by half or
>quarter what can I do.
>
>For ex- Range(1,3,0.5) I want it gives Output as [1 1.5 2 2.5 3)
>
>I am requesting to change the nature of increment number nature in above
>example so that we can increase the number with half or quarter any point
>value.
>
>Your Sincerely
>
>Aditya Gautam
>Saharsa (Bihar)
>India
>Postal Code- 852201

As was indicated, Range(1, 3, 0.5) if legal would generate ([1, 1.5, 2,
2.5] because range excludes the top value. This case happens to work in
the sense that if Python allowed it, this is the result that would come
out. On the other hand, the very similar Range(1, 3, 0.4) would be need
very detailed knowledge to predict, it could return [1, 1.4, 1.8, 2.2,
2.6] as expected or [1, 1.4, 1.8, 2.2, 2.6, 3.0]. The issue is that
there is no such exact number in binary floating point as 0.4, (it is
like trying to write out exactly 1/3), so the actual value used for 0.4
will be either slightly higher (where you get the expected value) or
slightly lower (where you would get the top 'excluded' value listed).
This sort of unpredictability is part of the difficulty dealing with
floating point.

As was pointed out, you can scale the range, or build your own generator
to get what you want.

-- 
Richard Damon

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


Re: About float/double type number in range.

2020-08-26 Thread Peter J. Holzer
On 2020-08-26 22:40:36 +1200, dn via Python-list wrote:
> On 26/08/2020 19:58, Joel Goldstick wrote:
> > On Wed, Aug 26, 2020 at 3:43 AM ADITYA  wrote:
> > > Dear Sir/Ma’am
> > > 
> > > I am requesting you to satisfy me about float number in Range
> > >     function, because in the argument of range we can take integer
> > > but not double or float whenever double as well as float are
> > > integer in nature but when we use double/float in, it gives
> > > error that- “'float' object cannot be interpreted as an
> > > integer.” If we want to increment the number by half or
> > > quarter what can I do.
> > > 
> > > For ex- Range(1,3,0.5) I want it gives Output as [1 1.5 2 2.5 3)
> > > 
> > 
> > Take a look at this:
> > > > > l = [i/2 for i in range(2,7)]
> > > > > l
> > [1.0, 1.5, 2.0, 2.5, 3.0]
> 
> 
> This is a neat solution! To make it more user-friendly, the above needs to
> be wrapped in a convenience function that the user can call using arguments
> like "(1,3,0.5)" and not have to think about the 'multiplies' and 'divides'.
> 
[...]
> <<< Code NB Python v3.8 >>>
> def fp_range( start:float, stop:float, step:float=1.0 )->float:
> """Generate a range of floating-point numbers."""
> if stop <= start:
> raise OverflowError( "RangeError: start must be less than stop" )
> x = start
> while x < stop:
> yield x
> x += step

This is almost the same solution as I came up with, but note that this
is not quote the same as what Joel proposed. Repeated addition is not
the same as multiplication with floating point numbers. 

A generator based on Joel's idea would look like this:

def fp_range(start, end, step):
v = start
n = int(math.ceil((end - start) / step))
for i in range(n):
yield start + i * step

(I omitted the OverflowError: range() doesn't raise one, either)

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: About float/double type number in range.

2020-08-26 Thread dn via Python-list

On 26/08/2020 19:58, Joel Goldstick wrote:

On Wed, Aug 26, 2020 at 3:43 AM ADITYA  wrote:


Dear Sir/Ma’am

I am requesting you to satisfy me about float number in Range function,
because in the argument of range we can take integer but not double or
float whenever double as well as float are integer in nature but when we
use double/float in, it gives error that- “'float' object cannot be
interpreted as an integer.” If we want to increment the number by half or
quarter what can I do.

    For ex- Range(1,3,0.5) I want it gives Output as [1 1.5 2 2.5 3)



Take a look at this:

l = [i/2 for i in range(2,7)]
l

[1.0, 1.5, 2.0, 2.5, 3.0]



This is a neat solution! To make it more user-friendly, the above needs 
to be wrapped in a convenience function that the user can call using 
arguments like "(1,3,0.5)" and not have to think about the 'multiplies' 
and 'divides'.


The problem with constructing such a list is that it is 'expensive', ie 
if the range is large, more storage-space will be required. In the same 
way that range() moved to a storage-averse model in Python3, herewith a 
pair of generator solutions - it might be quite fun to compare the 
performances (PSL's time library).


My first thought was that the count() from the itertools library enables 
one to step using a floating-point number. So, herewith two 
generator-based solutions:-



<<< Code NB Python v3.8 >>>
def fp_range( start:float, stop:float, step:float=1.0 )->float:
"""Generate a range of floating-point numbers."""
if stop <= start:
raise OverflowError( "RangeError: start must be less than stop" )
x = start
while x < stop:
yield x
x += step

try:
for fp_number in fp_range( 1, 3, 0.5 ):
print( fp_number )
except OverflowError as e:
print( e )

print( "*"*12 )

try:
for fp_number in fp_range( 1, 3, 0.25 ):
print( fp_number )
except OverflowError as e:
print( e )

print( "+"*12 )
import itertools

def fp_iter( start:float, stop:float, step:float=1.0 )->float:
"""Generate a range of floating-point numbers using 
itertools.count()."""

if stop <= start:
raise OverflowError( "RangeError: start must be less than stop" )
for x in itertools.count( start, step ):
if x >= stop:
break
yield x


for fp_number in fp_iter( 1, 3, 0.5 ):
print( fp_number )

print( "*"*12 )

for fp_number in fp_iter( 1, 3, 0.25 ):
print( fp_number )

print( "*"*12 )

try:
for fp_number in fp_iter( 3, 1, 0.5 ):
print( fp_number )
except OverflowError as e:
print( e )


<<< Console.out >>>

1
1.5
2.0
2.5

1
1.25
1.5
1.75
2.0
2.25
2.5
2.75

1
1.5
2.0
2.5

1
1.25
1.5
1.75
2.0
2.25
2.5
2.75

RangeError: start must be less than stop

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: About float/double type number in range.

2020-08-26 Thread Joel Goldstick
On Wed, Aug 26, 2020 at 3:43 AM ADITYA  wrote:
>
>Dear Sir/Ma’am
>
>I am requesting you to satisfy me about float number in Range function,
>because in the argument of range we can take integer but not double or
>float whenever double as well as float are integer in nature but when we
>use double/float in, it gives error that- “'float' object cannot be
>interpreted as an integer.” If we want to increment the number by half or
>quarter what can I do.
>
>For ex- Range(1,3,0.5) I want it gives Output as [1 1.5 2 2.5 3)
>

Take a look at this:
>>> l = [i/2 for i in range(2,7)]
>>> l
[1.0, 1.5, 2.0, 2.5, 3.0]
>>>
The first line is a list comprehension which is a convenient way to
produce a list by performing an operation on each element in range.

In your code, you set the end of the range to 3 which will not include
3.  It stops at 2.
>
>
>I am requesting to change the nature of increment number nature in above
>example so that we can increase the number with half or quarter any point
>value.
>
   if you want to increase by 1/4, use a range that is 4 times normal
integers. and divide each element by 4
>
>Your Sincerely
>
>Aditya Gautam
>
>Saharsa (Bihar)
>
>India
>
>Postal Code- 852201
>
>
>
>
>
>
>
>
>
>
>
>Sent from [1]Mail for Windows 10
>
>
>
>[2][IMG] Virus-free. [3]www.avg.com
>
> References
>
>Visible links
>1. https://go.microsoft.com/fwlink/?LinkId=550986
>2. 
> http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient
>3. 
> http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
-- 
https://mail.python.org/mailman/listinfo/python-list


About float/double type number in range.

2020-08-26 Thread ADITYA
   Dear Sir/Ma’am

   I am requesting you to satisfy me about float number in Range function,
   because in the argument of range we can take integer but not double or
   float whenever double as well as float are integer in nature but when we
   use double/float in, it gives error that- “'float' object cannot be
   interpreted as an integer.” If we want to increment the number by half or
   quarter what can I do.

   For ex- Range(1,3,0.5) I want it gives Output as [1 1.5 2 2.5 3)

    

   I am requesting to change the nature of increment number nature in above
   example so that we can increase the number with half or quarter any point
   value.

    

   Your Sincerely

   Aditya Gautam

   Saharsa (Bihar)

   India

   Postal Code- 852201

    

    

    

    

    

   Sent from [1]Mail for Windows 10

    

   [2][IMG] Virus-free. [3]www.avg.com

References

   Visible links
   1. https://go.microsoft.com/fwlink/?LinkId=550986
   2. 
http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient
   3. 
http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Button press event - event handling and picking: IndexError: list index out of range

2020-06-09 Thread Cousin Stanley
Caledonian26 wrote:


> However, I keep getting the error: 
> 
>   IndexError: list index out of range. 
> 
>  Could anyone give me a helping hand 
>  as to where I am going wrong?
> 

  I appended a single arbitrary value for limits  
  since the  limits  list had not been previously
  initialized  
  
  

  colourofbars = [ ]

  for key , value in dict_means.items() :

  limits.append( 3000 )

  if limits[ 0 ] > ( key + ( value ) ) :
  

  This fix gets past the  index out of range  error
  and produces a plot which might let you proceed
  to the next problem you might encounter 


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


Re: Button press event - event handling and picking: IndexError: list index out of range

2020-06-07 Thread DL Neil via Python-list

On 8/06/20 10:38 AM, MRAB wrote:

On 2020-06-07 23:24, DL Neil via Python-list wrote:

On 8/06/20 7:06 AM, Caledonian26 wrote:
...

However, I keep getting the error: IndexError: list index out of 
range. Could anyone give me a helping hand as to where I am going wrong?



When things go wrong, Python tries to be helpful by providing a
"traceback". Please copy-paste the entire traceback, to help us help you.

The error-message says that (somewhere) a list is being used *but* the
index is pointing to an element that does not exist, eg the fifth
element of a list that contains only three members.

Short answer: What you could do, is add a temporary print() to show you
the exact value of the list index. Thus, giving you a pointer/where to
back-track, to find the source of the problem...

The longer answer: learning to use a debugger or a 'visual' IDE/web-tool.

FYI, that's the same good advice that ChrisA gave yesterday in reply to 
the same post. See the thread "Applied Data Science with Python - 
Assignment 2.3: clicking on chart to select Y values".



Apologies @MRAB, didn't realise the duplication. I think I came to that 
thread late, noticed @Chris (and yourself?) had responded, deleted, and 
moved-on.


--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Button press event - event handling and picking: IndexError: list index out of range

2020-06-07 Thread MRAB

On 2020-06-07 23:24, DL Neil via Python-list wrote:

On 8/06/20 7:06 AM, Caledonian26 wrote:
...


However, I keep getting the error: IndexError: list index out of range. Could 
anyone give me a helping hand as to where I am going wrong?



When things go wrong, Python tries to be helpful by providing a
"traceback". Please copy-paste the entire traceback, to help us help you.

The error-message says that (somewhere) a list is being used *but* the
index is pointing to an element that does not exist, eg the fifth
element of a list that contains only three members.

Short answer: What you could do, is add a temporary print() to show you
the exact value of the list index. Thus, giving you a pointer/where to
back-track, to find the source of the problem...

The longer answer: learning to use a debugger or a 'visual' IDE/web-tool.

FYI, that's the same good advice that ChrisA gave yesterday in reply to 
the same post. See the thread "Applied Data Science with Python - 
Assignment 2.3: clicking on chart to select Y values".

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


Re: Button press event - event handling and picking: IndexError: list index out of range

2020-06-07 Thread DL Neil via Python-list

On 8/06/20 7:06 AM, Caledonian26 wrote:
...


However, I keep getting the error: IndexError: list index out of range. Could 
anyone give me a helping hand as to where I am going wrong?



When things go wrong, Python tries to be helpful by providing a 
"traceback". Please copy-paste the entire traceback, to help us help you.


The error-message says that (somewhere) a list is being used *but* the 
index is pointing to an element that does not exist, eg the fifth 
element of a list that contains only three members.


Short answer: What you could do, is add a temporary print() to show you 
the exact value of the list index. Thus, giving you a pointer/where to 
back-track, to find the source of the problem...


The longer answer: learning to use a debugger or a 'visual' IDE/web-tool.
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Button press event - event handling and picking: IndexError: list index out of range

2020-06-07 Thread Caledonian26
I have the following command below.

The overall aim is to allow the user to select a Y-value by pressing on the bar 
graph. The colour of each bar should then change depending on what this Y-value 
is.

import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib.colors
np.random.seed(12345)

df = pd.DataFrame({"values":[np.random.normal(32000,20,3650).mean(), 
   np.random.normal(43000,10,3650).mean(), 
   np.random.normal(43500,14,3650).mean(), 
   np.random.normal(48000,7,3650).mean()], 
  "index":[1992,1993,1994,1995]})

standarderrors1992 = stats.sem(np.random.normal(32000,20,3650))
standarderrors1993 = stats.sem(np.random.normal(43000,10,3650))
standarderrors1994 = stats.sem(np.random.normal(43500,14,3650))
standarderrors1995 = stats.sem(np.random.normal(48000,7,3650)) 
add1992 = 1.96*standarderrors1992
add1993 = 1.96*standarderrors1993
add1994 = 1.96*standarderrors1994 
add1995 = 1.96*standarderrors1995
mean1992 = np.random.normal(32000,20,3650).mean()
mean1993 = np.random.normal(43000,10,3650).mean()
mean1994 = np.random.normal(43500,14,3650).mean()
mean1995 = np.random.normal(48000,7,3650).mean()
labels = [1992,1993,1994,1995]
add = [add1992,add1992,add1994,add1995]

1. This first part organises the raw data.

limits = []

def onclick(event):
plt.cla()
plt.bar(df["index"].values,df["values"].values,align='center', 
alpha=0.5,yerr=add)
plt.xticks(labels)
limit = event.ydata
limits.append(limit)
if len(limits) >= 1:

plt.gcf().canvas.mpl_disconnect(plt.gcf().canvas.mpl_connect('button_press_event',
 onclick))

plt.gcf().canvas.mpl_connect('button_press_event', onclick)

2. This next part allows the user to press on the graph to select a Y value. 
This should be assigned to the variable 'limits'

 dict = {mean1992:add1992,mean1993:add1993,mean1994:add1994,mean1995:add1995}
  colourofbars = []
  for key,value in dict.items():
  if limits[0] > (key+(value)):
  colour = 1 
  colourofbars.append(colour)
  elif limits[0] < (key-(value)):
  colour = 0 
  colourofbars.append(colour)
  elif (limits[0] < (key+(value))) & (limits[0] > (key-(value))): 
  colour = ((key+(value))-limits[0])/((key+value)-(key-value)) 
  colourofbars.append(colour)
df["colourofbars"] = colourofbars

3. Here, the list 'colourofbars' is appended based on the data above, and added 
as a column to the dataframe 'df'.

cmap = plt.cm.rainbow
norm = matplotlib.colors.Normalize(vmin=1.5, vmax=4.5)
plt.bar(df["index"].values,df["values"].values,color=cmap(norm(df["colourofbars"].values)),align='center',
 alpha=0.5,yerr=add)
plt.xticks(labels)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
plt.gcf().colorbar(sm)
plt.show()

4. Here, a different colour is assigned to each bar in the bar chart depending 
on the values in the column 'colourofbars'. I then try to plot a legend showing 
this colour gradient scale.

However, I keep getting the error: IndexError: list index out of range. Could 
anyone give me a helping hand as to where I am going wrong?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Determining index of range of values in a matrix

2020-05-19 Thread DL Neil via Python-list

On 19/05/20 6:40 AM, swaroop.sahoo...@gmail.com wrote:

Hi All,
I am using python for doing the following:
I have a matrix which has dimension of 174*993.
Each row of the matrix has some numbers in the range of 30-30.5.
I would like to determine the index of the numbers in the range of 30-30.5 in 
each row.
I can determine the index of the numbers in each row by using 
result1=np.where(np.logical_and(R[i,:]>= 30, R[i,:]<= 30.3))
But I would like to put the indexes in a matrix.
That is difficult because the number of indexes in each row will be different.
Can anyone help.



I'm probably less than sure that I've understood the problem. How will 
the indexes be used once the second 'matrix' is built?


Might it help to include some examples of data-rows, plus the expected 
index-row?


Are we to assume that you are using np?


As you allude, the usual structure of a "matrix" is that the number of 
'columns' in each 'row' is the same. However, the indexes might 
constitute a "sparse matrix".


Python however, has no 'matrix' data-structure, but does allow lists to 
contain lists (or dict[ionaries] to contain dicts) as a 2D 
data-structure. A list has no constraint, and no expectation that each 
'row' has the same number of columns.

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Determining index of range of values in a matrix

2020-05-18 Thread swaroop . sahoo769
Hi All,
I am using python for doing the following:
I have a matrix which has dimension of 174*993.
Each row of the matrix has some numbers in the range of 30-30.5.
I would like to determine the index of the numbers in the range of 30-30.5 in 
each row.
I can determine the index of the numbers in each row by using 
result1=np.where(np.logical_and(R[i,:]>= 30, R[i,:]<= 30.3))
But I would like to put the indexes in a matrix.
That is difficult because the number of indexes in each row will be different.
Can anyone help.

Regards,
Swaroop
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Accumulate , Range and Zeros

2019-07-13 Thread Abdur-Rahmaan Janhangeer
oh not a real bug, i thought the effect had to do with generator working
rather a simple times 0

Abdur-Rahmaan Janhangeer
Mauritius

On Sat, 13 Jul 2019, 16:24 Chris Angelico,  wrote:

> On Sat, Jul 13, 2019 at 10:02 PM Abdur-Rahmaan Janhangeer
>  wrote:
> >
> > @Thomas thought was a generator bug since instead of returning the usual
> > nums it was returning 0 0 0 ...
>
> When you find a bug or strange bit of behaviour, first make sure you
> can reproduce it. Then create a small, self-contained program, just
> enough to demonstrate what's going on. Post that code. Don't make us
> guess :)
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Accumulate , Range and Zeros

2019-07-13 Thread Chris Angelico
On Sat, Jul 13, 2019 at 10:02 PM Abdur-Rahmaan Janhangeer
 wrote:
>
> @Thomas thought was a generator bug since instead of returning the usual
> nums it was returning 0 0 0 ...

When you find a bug or strange bit of behaviour, first make sure you
can reproduce it. Then create a small, self-contained program, just
enough to demonstrate what's going on. Post that code. Don't make us
guess :)

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


Re: Accumulate , Range and Zeros

2019-07-13 Thread Abdur-Rahmaan Janhangeer
@Thomas thought was a generator bug since instead of returning the usual
nums it was returning 0 0 0 ...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Accumulate , Range and Zeros

2019-07-13 Thread Thomas Jollans
On 13/07/2019 11:54, Abdur-Rahmaan Janhangeer wrote:
> Greetings,
> 
> Given this snippet
> 
> from itertools import *
> import operator
> 
> 
> x = [1, 2, 3] # [0, 1, 2, 3, ..., 10]
> 
> y = accumulate(x, operator.mul)
> 
> print(list(y))
> 
> why does x = list(range(5)) produces only zeros?

What would you expect it to produce?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Accumulate , Range and Zeros

2019-07-13 Thread Abdur-Rahmaan Janhangeer
@Frank

So simple. Thanks!

Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Accumulate , Range and Zeros

2019-07-13 Thread Dan Sommers




On 7/13/19 5:54 AM, Abdur-Rahmaan Janhangeer wrote:
> > Greetings,
> >
> > Given this snippet
> >
> > from itertools import *
> > import operator
> >
> >
> > x = [1, 2, 3] # [0, 1, 2, 3, ..., 10]
> >
> > y = accumulate(x, operator.mul)
> >
> > print(list(y))
> >
> > why does x = list(range(5)) produces only zeros?

I see two things going on here.

(1) Don't type snippets of code and results from memory, or
in bits and pieces from an interactive session.  Copy and
paste exactly the code that ran and the output that it
produced.

(2) What is range(5)?  Okay, what is list(range(5))?  What
do you (the person) get when you multiply those five
integers together?

HTH,
Dan
--
https://mail.python.org/mailman/listinfo/python-list


Re: Accumulate , Range and Zeros

2019-07-13 Thread Frank Millman

On 2019-07-13 11:54 AM, Abdur-Rahmaan Janhangeer wrote:

Greetings,

Given this snippet

from itertools import *
import operator


x = [1, 2, 3] # [0, 1, 2, 3, ..., 10]

y = accumulate(x, operator.mul)

print(list(y))

why does x = list(range(5)) produces only zeros?



That is an easy one.

By default, range() starts from 0. Anything multiplied by 0 equals 0. So 
you can multiply as many numbers as you like, if the first one is 0, the 
rest will also be 0.


QED

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


Accumulate , Range and Zeros

2019-07-13 Thread Abdur-Rahmaan Janhangeer
Greetings,

Given this snippet

from itertools import *
import operator


x = [1, 2, 3] # [0, 1, 2, 3, ..., 10]

y = accumulate(x, operator.mul)

print(list(y))

why does x = list(range(5)) produces only zeros?

-- 
Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Copying a row from a range of Excel files to another

2019-06-28 Thread Cecil Westerhof
MRAB  writes:

> On 2019-06-26 22:14, Cecil Westerhof wrote:
>> MRAB  writes:
>>
>>> Does Workbook support the 'with' statement?
>>>
>>> If it does, then that's the best way of doing it.
>>>
>>> (Untested)
>>>
>>> with Workbook() as wb_out:
>>> for filepath in filepathArr:
>>> current_row = []
>>>
>>> with load_workbook(filepath) as wb_in:
>>> for cell in wb_in.active[src_row]:
>>> current_row.append(cell.value)
>>>
>>> wb_out.active.append(current_row)
>>>
>>> wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') +
>>> report_end)
>>
>> It seems not. I get AttributeError.
>>
> You didn't say which line.

I made a minimalist program to show it:
#!/usr/bin/env python3


from openpyxl import Workbook


with Workbook() as wb_out:
print('In loop')
print('After loop')

This results in:
Traceback (most recent call last):
  File "./test.py", line 7, in 
with Workbook() as wb_out:
AttributeError: __exit__


> Anyway, if Workbooks are closed using a method called "close", you can
> wrap them in a "closing" context manager:

That seems to work. I changed it to:
#!/usr/bin/env python3


from contextlib   import closing
from datetime import datetime
from openpyxl import Workbook


with closing(Workbook()) as wb_out:
print('In loop')
wb_out.save('testing_' + datetime.now().strftime('%Y-%m-%d') + '.xlsx')
print('After loop')

And I see:
In loop
After loop

And a testing Excel file.

Thanks.

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


Re: Copying a row from a range of Excel files to another

2019-06-26 Thread Sayth Renshaw
 Cecil Westerhof  wrote:
> I was asked to copy a certain line from about 300 Excel lines to a new
> Excel file. That is not something I would like to do by hand and I
> immediately thought: that should be possible with Python.
> 
> And it is. I was surprised how fast I could write that with openpyxl.
> My first try was not very neat, but a proof of concept. Then by
> looking better at the possibilities I could get much cleaner code. But
> I am still not completely happy. At the moment I have the following
> code:
> wb_out = Workbook()
> for filepath in filepathArr:
> current_row = []
> wb_in   = load_workbook(filepath)
> for cell in wb_in.active[src_row]:
> current_row.append(cell.value)
> wb_out.active.append(current_row)
> wb_in.close()
> wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') + 
> report_end)
> wb_out.close()
> 
> I could not find a way to copy a row from one workbook to another.
> That is why I put the row in current_row and do an append. Am I
> overlooking something, or is that really the way to do this?
> 
> 
> 
> -- 
> Cecil Westerhof

Pandas may work out better.

import pandas as pd

df = pd.read_excel('spreadsheet')
# find the row by filtering with regex
df2 = df.'column'.str.contains('criteria as regex')
df2.pd.save_excel('output.xlsx')

Cheers

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


Re: Copying a row from a range of Excel files to another

2019-06-26 Thread MRAB

On 2019-06-26 22:14, Cecil Westerhof wrote:

MRAB  writes:


Does Workbook support the 'with' statement?

If it does, then that's the best way of doing it.

(Untested)

with Workbook() as wb_out:
for filepath in filepathArr:
current_row = []

with load_workbook(filepath) as wb_in:
for cell in wb_in.active[src_row]:
current_row.append(cell.value)

wb_out.active.append(current_row)

wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') +
report_end)


It seems not. I get AttributeError.


You didn't say which line.

Anyway, if Workbooks are closed using a method called "close", you can 
wrap them in a "closing" context manager:


from contextlib import closing

with closing(Workbook()) as wb_out:
for filepath in filepathArr:
current_row = []

with closing(load_workbook(filepath)) as wb_in:
for cell in wb_in.active[src_row]:
current_row.append(cell.value)
wb_out.active.append(current_row)

wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') 
+ report_end)

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


Re: Copying a row from a range of Excel files to another

2019-06-26 Thread Cecil Westerhof
MRAB  writes:

> Does Workbook support the 'with' statement?
>
> If it does, then that's the best way of doing it.
>
> (Untested)
>
> with Workbook() as wb_out:
> for filepath in filepathArr:
> current_row = []
>
> with load_workbook(filepath) as wb_in:
> for cell in wb_in.active[src_row]:
> current_row.append(cell.value)
>
> wb_out.active.append(current_row)
>
> wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') +
> report_end)

It seems not. I get AttributeError.

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


Re: Copying a row from a range of Excel files to another

2019-06-26 Thread MRAB

On 2019-06-26 13:15, Cecil Westerhof wrote:

Cecil Westerhof  writes:


I was asked to copy a certain line from about 300 Excel lines to a new
Excel file. That is not something I would like to do by hand and I
immediately thought: that should be possible with Python.

And it is. I was surprised how fast I could write that with openpyxl.
My first try was not very neat, but a proof of concept. Then by
looking better at the possibilities I could get much cleaner code. But
I am still not completely happy. At the moment I have the following
code:
wb_out = Workbook()
for filepath in filepathArr:
current_row = []
wb_in   = load_workbook(filepath)
for cell in wb_in.active[src_row]:
current_row.append(cell.value)
wb_out.active.append(current_row)
wb_in.close()
wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') + report_end)
wb_out.close()

I could not find a way to copy a row from one workbook to another.
That is why I put the row in current_row and do an append. Am I
overlooking something, or is that really the way to do this?


I am not used to writing GUI programs. (I have to learn tkinter also.)
What is the best way to handle potential errors? It could go wrong on
line 1, 4, 5, 7, 8, 9 and 10. Should I catch every exception alone, or
all together, or something in between?


I rewrote it like:
 wb_in  = None
 wb_out = None
 try:
 wb_out = Workbook()
 for filepath in filepathArr:
 current_row = []
 wb_in   = load_workbook(filepath)
 for cell in wb_in.active[src_row]:
 current_row.append(cell.value)
 wb_out.active.append(current_row)
 wb_in.close()
 wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') + 
report_end)
 wb_out.close()
 messagebox.showinfo(info_str, created_report)
 except Exception as err:
 if wb_in:
 wb_in.close()
 if wb_out:


Missing ():

 wb_close
 messagebox.showerror(error_str,
  error_generate + '\n\n\n\n' + str(err))

Is it necessary to close the workbooks to circumvent a resource leak?
Is it a problem when a workbook is closed two times? If so I need to
make sure that this is not possible.


Does Workbook support the 'with' statement?

If it does, then that's the best way of doing it.

(Untested)

with Workbook() as wb_out:
for filepath in filepathArr:
current_row = []

with load_workbook(filepath) as wb_in:
for cell in wb_in.active[src_row]:
current_row.append(cell.value)

wb_out.active.append(current_row)

wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') 
+ report_end)

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


Re: Copying a row from a range of Excel files to another

2019-06-26 Thread Cecil Westerhof
Cecil Westerhof  writes:

> Is it necessary to close the workbooks to circumvent a resource
> leak?

Still like to know. When not necessary it is better not to cloes them
I think.


> Is it a problem when a workbook is closed two times? If so I need to
> make sure that this is not possible.

That is not a problem. I tried it and it just works.

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


Re: Copying a row from a range of Excel files to another

2019-06-26 Thread Cecil Westerhof
Cecil Westerhof  writes:

> I was asked to copy a certain line from about 300 Excel lines to a new
> Excel file. That is not something I would like to do by hand and I
> immediately thought: that should be possible with Python.
>
> And it is. I was surprised how fast I could write that with openpyxl.
> My first try was not very neat, but a proof of concept. Then by
> looking better at the possibilities I could get much cleaner code. But
> I am still not completely happy. At the moment I have the following
> code:
> wb_out = Workbook()
> for filepath in filepathArr:
> current_row = []
> wb_in   = load_workbook(filepath)
> for cell in wb_in.active[src_row]:
> current_row.append(cell.value)
> wb_out.active.append(current_row)
> wb_in.close()
> wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') + 
> report_end)
> wb_out.close()
>
> I could not find a way to copy a row from one workbook to another.
> That is why I put the row in current_row and do an append. Am I
> overlooking something, or is that really the way to do this?
>
>
> I am not used to writing GUI programs. (I have to learn tkinter also.)
> What is the best way to handle potential errors? It could go wrong on
> line 1, 4, 5, 7, 8, 9 and 10. Should I catch every exception alone, or
> all together, or something in between?

I rewrote it like:
wb_in  = None
wb_out = None
try:
wb_out = Workbook()
for filepath in filepathArr:
current_row = []
wb_in   = load_workbook(filepath)
for cell in wb_in.active[src_row]:
current_row.append(cell.value)
wb_out.active.append(current_row)
wb_in.close()
wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') + 
report_end)
wb_out.close()
messagebox.showinfo(info_str, created_report)
except Exception as err:
if wb_in:
wb_in.close()
if wb_out:
wb_close
messagebox.showerror(error_str,
 error_generate + '\n\n\n\n' + str(err))

Is it necessary to close the workbooks to circumvent a resource leak?
Is it a problem when a workbook is closed two times? If so I need to
make sure that this is not possible.

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


Copying a row from a range of Excel files to another

2019-06-26 Thread Cecil Westerhof
I was asked to copy a certain line from about 300 Excel lines to a new
Excel file. That is not something I would like to do by hand and I
immediately thought: that should be possible with Python.

And it is. I was surprised how fast I could write that with openpyxl.
My first try was not very neat, but a proof of concept. Then by
looking better at the possibilities I could get much cleaner code. But
I am still not completely happy. At the moment I have the following
code:
wb_out = Workbook()
for filepath in filepathArr:
current_row = []
wb_in   = load_workbook(filepath)
for cell in wb_in.active[src_row]:
current_row.append(cell.value)
wb_out.active.append(current_row)
wb_in.close()
wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') + report_end)
wb_out.close()

I could not find a way to copy a row from one workbook to another.
That is why I put the row in current_row and do an append. Am I
overlooking something, or is that really the way to do this?


I am not used to writing GUI programs. (I have to learn tkinter also.)
What is the best way to handle potential errors? It could go wrong on
line 1, 4, 5, 7, 8, 9 and 10. Should I catch every exception alone, or
all together, or something in between?

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


Re: Why I am getting IndexError: tuple index out of range when converting a float value to a string?

2019-06-11 Thread Terry Reedy

On 6/11/2019 1:04 PM, Rob Gaddi wrote:

On 6/11/19 9:52 AM, madhavanbom...@gmail.com wrote:

I wrote the following lines of code:

xm = np.nanmean(x[indx],axis=None,dtype=float)
xsd = np.nanstd(x[indx],axis=None,dtype=float)

type(xm)    # np.float64
type(xsd    # np.float64

print(xm)  # 0.5414720812182742
print(xsd) # 0.15748041033663002

print(str("{6.5f}".format(xm)))

I get the following error:

IndexError: tuple index out of range

Can someone suggest me why I am getting this error and how to overcome 
this?


Show us the full traceback after expanding and reducing the example to 
the minimum needed to exhibit the problem.



print(str("{:6.5f}".format(xm)))

You want to apply the format 6.5f to the autoindexed element.


Which works fine as it is.

>>> xm = 3.0
>>> print(str("{:6.5f}".format(xm)))
3.0


You could also explicitly index the 1st element (#0) as {0:6.5f}.


He could, but it makes no difference for the print statement above.

Applying str to an str is redundant, as it applying it to a print argument.

>>> print("{0:6.5f}".format(xm))
3.0


--
Terry Jan Reedy


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


Re: Why I am getting IndexError: tuple index out of range when converting a float value to a string?

2019-06-11 Thread Rob Gaddi

On 6/11/19 9:52 AM, madhavanbom...@gmail.com wrote:

I wrote the following lines of code:

xm = np.nanmean(x[indx],axis=None,dtype=float)
xsd = np.nanstd(x[indx],axis=None,dtype=float)

type(xm)# np.float64
type(xsd# np.float64

print(xm)  # 0.5414720812182742
print(xsd) # 0.15748041033663002

print(str("{6.5f}".format(xm)))

I get the following error:

IndexError: tuple index out of range

Can someone suggest me why I am getting this error and how to overcome this?

Thanks in advance



print(str("{:6.5f}".format(xm)))

You want to apply the format 6.5f to the autoindexed element.  You could 
also explicitly index the 1st element (#0) as {0:6.5f}.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Why I am getting IndexError: tuple index out of range when converting a float value to a string?

2019-06-11 Thread madhavanbomidi
I wrote the following lines of code:

xm = np.nanmean(x[indx],axis=None,dtype=float)   
xsd = np.nanstd(x[indx],axis=None,dtype=float)

type(xm)# np.float64
type(xsd# np.float64

print(xm)  # 0.5414720812182742
print(xsd) # 0.15748041033663002

print(str("{6.5f}".format(xm)))

I get the following error:

IndexError: tuple index out of range

Can someone suggest me why I am getting this error and how to overcome this?

Thanks in advance
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Sum of few numbers by using for and range

2019-02-17 Thread DL Neil

On 18/02/19 8:32 AM, Chris Angelico wrote:

On Mon, Feb 18, 2019 at 6:12 AM DL Neil  wrote:

The reason this course caught my attention (and which is relevant to
you, per Chris' and Dennis' recent advice) is that the course revolves
around an 'active textbook'. This intersperses learning material with
mastery exercises, and pertinently, uses a 'widget' which steps through
code, line-by-line, showing exactly what is happening to each variable.
I was impressed!


That sounds like an EXCELLENT way to do the second part - running the
code to see if you were right. I would still recommend doing it 100%
manually first, *writing down* your expectations, and only *then*
letting the computer do it. It's easy to watch the computer do
something and go "yes, of course that's what happens", but to still
not be able to replicate it yourself. True comprehension means being
able to predict what will happen.

Consider it like a falsifiable hypothesis in scientific research. "I
expect that, when I do X, Y, and Z, the result will be Q." Then you
actually perform those steps, and see what the result is. Were you
right? If not, how do you modify your expectations/hypothesis to
correct it? It's the last step that is the most interesting, because
that's where you truly learn. (And sometimes, that learning is
expanding the corpus of human knowledge. It's only when you disprove
your expectations that you can begin to pin down something like "oh so
time flows at different rates depending on gravity" or "huh, so it
turns out black-body radiation doesn't behave the way all the math
said it would".)


+1

For reference Chris (et al):
The 'active textbook' offers 'windows' which seem to be Idle, but in a 
controlled and prescribed environment. So, the learner first writes 
his/her code, and only then can run and/or step-through, as described.



+for ^Bart:
IIRC the early stages of the U.Mich/Coursera Py3 Pgmg course included 
coverage of "accumulators", which concept you have yet to learn - and 
certainly lists and ranges appear. Thus dealing with both of the 
conceptual errors causing grief in the original code-snippet. All the best!



--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Sum of few numbers by using for and range

2019-02-17 Thread Chris Angelico
On Mon, Feb 18, 2019 at 6:12 AM DL Neil  wrote:
> > sure you truly understand what is going on. Try to piece together what
> > a section of code is doing, step by step. Write down on a piece of
> > paper what the variables are at each point in the program. Then, AFTER
> > doing the work manually, run the code and see if you were right.
>
> +1
>
> The reason this course caught my attention (and which is relevant to
> you, per Chris' and Dennis' recent advice) is that the course revolves
> around an 'active textbook'. This intersperses learning material with
> mastery exercises, and pertinently, uses a 'widget' which steps through
> code, line-by-line, showing exactly what is happening to each variable.
> I was impressed!

That sounds like an EXCELLENT way to do the second part - running the
code to see if you were right. I would still recommend doing it 100%
manually first, *writing down* your expectations, and only *then*
letting the computer do it. It's easy to watch the computer do
something and go "yes, of course that's what happens", but to still
not be able to replicate it yourself. True comprehension means being
able to predict what will happen.

Consider it like a falsifiable hypothesis in scientific research. "I
expect that, when I do X, Y, and Z, the result will be Q." Then you
actually perform those steps, and see what the result is. Were you
right? If not, how do you modify your expectations/hypothesis to
correct it? It's the last step that is the most interesting, because
that's where you truly learn. (And sometimes, that learning is
expanding the corpus of human knowledge. It's only when you disprove
your expectations that you can begin to pin down something like "oh so
time flows at different rates depending on gravity" or "huh, so it
turns out black-body radiation doesn't behave the way all the math
said it would".)

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


Re: Sum of few numbers by using for and range

2019-02-17 Thread DL Neil

^Bart,

Which course are you attempting?

What are you using as learning material?
(it seems ineffectual)

- further comments interspersed, below:-


On 18/02/19 5:30 AM, Chris Angelico wrote:

On Mon, Feb 18, 2019 at 3:26 AM ^Bart  wrote:

I need to do what I wrote in the subject but... I don't understand how
could I fix my code... :\



When you want homework help, it is extremely useful to post the entire
challenge you were given, not just a one-line summary. What are you
actually expected to do? What are the restrictions?


Also, are you aware that there is a separate email list "for folks who 
want to ask questions regarding how to learn computer programming with 
the Python language and its standard library."?

(https://mail.python.org/mailman/listinfo/tutor)



I suspect, from your last few posts, that you should not be taking
particular challenges, but should instead go back to the basics of how
Python works. Reread the earliest material in your course and make


+1

As explained earlier, asking helpful people 'here' to complete the task 
for you helps no-one!
- you haven't really learned, and are unlikely to have mastered 
techniques necessary to pursue employment or hobby-interests, in future

- you've asked community-minded folk to give-up their time
- your trainer is unlikely to be fooled for long...



sure you truly understand what is going on. Try to piece together what
a section of code is doing, step by step. Write down on a piece of
paper what the variables are at each point in the program. Then, AFTER
doing the work manually, run the code and see if you were right.


+1

I recently audited a set of courses (last one yet to be released) on 
Coursera, out of U.Mich (Michigan, USA): Python 3 Programming 
Specialization 
(https://www.coursera.org/specializations/python-3-programming). I'm not 
recommending it particularly - it doesn't fit with my personal approach 
(which may say more about me!)


NB Coursera uses a 'freemium' business model. In my context "audit" 
meant 'evaluation', but in Coursera-jargon it means $free. Paying for 
such a course adds invitations to participate in project work, (?)final 
exam, and one hopes, earn a certificate.


The reason this course caught my attention (and which is relevant to 
you, per Chris' and Dennis' recent advice) is that the course revolves 
around an 'active textbook'. This intersperses learning material with 
mastery exercises, and pertinently, uses a 'widget' which steps through 
code, line-by-line, showing exactly what is happening to each variable. 
I was impressed!


In 'the good old days', we used to talk about having a 'paper computer'. 
In appearance, this was almost exactly like the above - where we could 
'see' exactly (what we thought) was happening inside the CPU. It was a 
testing/debugging tool before the first line of code hit the Python (or 
whichever) interpreter/compiler. (who says Test-driven Development is a 
"new" idea?). In short, it is an excellent tool for visualising learning!


NB There is a Python Debugger tool which operates similarly, but the 
learning tool is illustrative in nature, cf diagnostic.


Having mentioned U.Mich/Coursera, one of the most famous Python courses 
available over-the-Internet is Dr Chuck's "Python for Everyone". I'm not 
aware if he has upgraded those to use the same active textbook tool. 
That said, it is an enormously-popular avenue for exploring Python!


--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Sum of few numbers by using for and range

2019-02-17 Thread Chris Angelico
On Mon, Feb 18, 2019 at 3:26 AM ^Bart  wrote:
>
> Hello!
>
> I need to do what I wrote in the subject but... I don't understand how
> could I fix my code... :\
>
> number1 = int( input("Insert the first number:"))
> number2 = int( input("Insert the second number:"))
> number3 = int( input("Insert the third number:"))
>
> print("Total amount is:")
>
> for x in range(number1,number3):
>  y = x+x
>  print(y)
>

When you want homework help, it is extremely useful to post the entire
challenge you were given, not just a one-line summary. What are you
actually expected to do? What are the restrictions?

I suspect, from your last few posts, that you should not be taking
particular challenges, but should instead go back to the basics of how
Python works. Reread the earliest material in your course and make
sure you truly understand what is going on. Try to piece together what
a section of code is doing, step by step. Write down on a piece of
paper what the variables are at each point in the program. Then, AFTER
doing the work manually, run the code and see if you were right.

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


Sum of few numbers by using for and range

2019-02-17 Thread ^Bart

Hello!

I need to do what I wrote in the subject but... I don't understand how 
could I fix my code... :\


number1 = int( input("Insert the first number:"))
number2 = int( input("Insert the second number:"))
number3 = int( input("Insert the third number:"))

print("Total amount is:")

for x in range(number1,number3):
y = x+x
print(y)

Regards.
^Bart
--
https://mail.python.org/mailman/listinfo/python-list


Re: range

2018-06-25 Thread Schachner, Joseph
Re: "I know I'm going to get flak for bringing this up this old issue, but 
remember when you used to write a for-loop and it involved creating an actual 
list of N integers from 0 to N-1 in order to iterate through them? Crazy.

But that has long been fixed - or so I thought. When I wrote, today:



    for i in range(1): pass  # 100 million



on Python 2, it used up 1.8GB, up to the limit of my RAM, and it took several 
minutes to regain control of my machine (and it never did finish). You don't 
expect that in 2018 when executing a simple empty loop.

On Py 2 you have to use xrange for large ranges - that was the fix.

Somebody however must have had to gently and tactfully point out the issue. I'm 
 afraid I'm not very tactful."



It HAS been fixed in Python 3, since the beginning of that branch.  In Python 3 
range is what xrange was in Python 2.  I used past tense there on purpose.



Python 2 actual demise is scheduled.  See: https://python3statement.org/

It's a list of project that have pledged to drop support for Python2.7 no later 
than January 1, 2020. You will recognize many of them: Pandas, IPython, NumPy, 
Matplotlib, Jupyter... etc



Anyone talking about the future of Python and features that might be added to 
Python really has to be talking about Python 3, because Python 2 support is 
already ramping down and will completely end on January 1, 2020.  The original 
plan was to end it in 2015, but the extra five years were added to give 
everyone plenty of time to switch.



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


Re: curious asymmetry in range limiting

2018-03-20 Thread Wolfgang Maier

On 03/20/2018 03:21 PM, Robin Becker wrote:

I don't know how I never came across this before, but there's a curious 
asymmetry in the way ranges are limited

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit 
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
  >>> s = '0123456789'
  >>> print(repr(s[-5:5]))
''
  >>> print(repr(s[5:15]))
'56789'
  >>>

why is the underflow start index treated so differently from the limit index 
overflow? I suppose there must be some reason, but it
eludes me.



It's because in the slice [-5:5] the -5 is not trying to access an 
element at an index < 0, but indicating the fifth-last element in the 
sequence.



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


Re: curious asymmetry in range limiting

2018-03-20 Thread Robin Becker

So eventually I tried this


C:\code\hg-repos\reportlab>\python36\python 
-c"s='0123456789';print(repr(s[-5:15]))"
'56789'

C:\code\hg-repos\reportlab>\python36\python 
-c"s='0123456789';print(repr(s[-6:15]))"
'456789'


and the light dawned :) seems the negative indexes rules apply to both



On 20/03/2018 14:21, Robin Becker wrote:

I don't know how I never came across this before, but there's a curious 
asymmetry in the way ranges are limited

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit 
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> s = '0123456789'
 >>> print(repr(s[-5:5]))
''
 >>> print(repr(s[5:15]))
'56789'
 >>>

why is the underflow start index treated so differently from the limit index overflow? I suppose there must be some reason, but it 
eludes me.



--
Robin Becker

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


curious asymmetry in range limiting

2018-03-20 Thread Robin Becker

I don't know how I never came across this before, but there's a curious 
asymmetry in the way ranges are limited

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit 
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '0123456789'
>>> print(repr(s[-5:5]))
''
>>> print(repr(s[5:15]))
'56789'
>>>

why is the underflow start index treated so differently from the limit index overflow? I suppose there must be some reason, but it 
eludes me.

--
Robin Becker

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


Re: Teaching the "range" function in Python 3

2017-07-02 Thread Rick Johnson
On Saturday, July 1, 2017 at 12:48:39 AM UTC-5, Christian Gollwitzer wrote:
> Am 30.06.17 um 04:33 schrieb Rick Johnson:
> > And to further drive home the point, you can manually
> > insert a list literal to prove this:
> > 
> >  >>> range(10)
> >  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> >  >>> for value in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
> >  ... print(value)
> >  ...
> >  0
> >  1
> 
> Now you have exactly missed the point that the OP was
> asking about. In Python 2, yes, this works and it is the
> way he has teached it to his students. Howver, in Python 3:

Nah, I didn't miss the point, i just forgot to pass in a
version number to my virtual python "fetch_answer" function --
which defaults to Python2.x

    def fetch_answer(question, pyver=2):
return database[pyver].get(question, "Urmm???")

>  >>> range(10)
> range(0, 10)
> 
> This is not helpful to understand what range does [in
> Python>=3.0], and this is the original question.

Yeah, and thanks for underscoring the obvious. ;-)

PS: Okay! Okay! So I forgot to call list on the range! So
sue me!!! ;-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Teaching the "range" function in Python 3

2017-07-02 Thread Rick Johnson
On Thursday, June 29, 2017 at 9:58:23 PM UTC-5, Chris Angelico wrote:
> On Fri, Jun 30, 2017 at 12:33 PM, Rick Johnson
> > A better *FIRST* example would be something like this:
> >
> > def add(x, y):
> > return x + y
> >
> > When teaching a student about functions, the first step is
> > to help them understand *WHY* they need to use functions,
> > and the second is to teach them how to define a function.
> > In my simplistic example, the practical necessity of
> > functions can be easily intuited by the student without
> > the distractions...
> 
> ... except that you've made your first function so trivial
> that it doesn't need to be a function. How does that help
> anyone understand why they need functions? 

The point, Christopher, is to showcase in the most simple
form possible, that functions package a block of code for
easy reuse. Actually this example showcases three major
elements of functions:

(1) That functions accept arguments. (in this
case, positional arguments. Keyword arguments and default
arguments can be introducted in an advanced lesson)

(2)That functions perform a specific task within the "body"
of the function. (No need to complicate the example by
turning it into a generator, calculating a Fibonacci
sequence, starting a new thread, or creating a class factory
for your effing bot-net!!!)

(3) That functions can return a value to the caller.

Easy peasy. ABC, 123. Get it?

> What's the point of writing "add(5, 7)" rather than "5 +
> 7"?

Does the acronym "DRY" mean anything to you?

Does the concept of "code reuse" mean anything to you?

Does the concept of creating a "general solution" as opposed
to a "specific solution" mean anything to you?

Of course, no programmer would require such a basic "add"
function like this since Python numeric types have
mathematical operations available (it would be as practical
as training wheels on a tour de france racing bike!), but
the point is to offer simple examples that anyone can
understand. For example, even a primary school student
understands how to add two numbers together to produce a
result, and has also been exposed to variables in basic
algebra:

   x + 3 = 10 (What is the value of x?)
   
   7 + y = 10 (What is the value of y?)
   
So any student with even a basic understanding of
mathematics can intuit that x and y are simply placeholders
for numeric values.

> So you need something else around the outside to justify
> even having a function at all.

Why? So i can teach a noob to write spaghetti code? Okay, just
for the Lulz factor, do you care to offer a code example?
I'd love to watch your squirm your way out of this one!

> In the example in the tutorial, the details ...
> 
> > ... of (1) doc-strings, (2) tuple unpacking, (3) an inner
> > loop structure, (4) implicitly writing to IO streams using
> > the print function, (5) using advanced features of the
> > print function, (6) more tuple unpacking (this time with a
> > twist of lime), (7) and an implicit newline insertion
> > using the print function
> 
> don't need to be explained at all! They *just work*. You
> also don't have to explain in detail how garbage collection
> works, the way that Python's object and type models work,
> or how the electrons in your CPU are kept from portalling
> across in a quantum tunnel. None of that matters. So I
> support the tutorial's example over yours.

Of course you do! Because you don't care if new programmers
are presented with poor examples. From your POV, if someone
else is suffering, it's not your problem.

> Chris "not-so-Angelic, oh?!"


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


  1   2   3   4   5   6   7   8   9   10   >