Re: A technique from a chatbot

2024-04-03 Thread Michael F. Stemper via Python-list

On 03/04/2024 13.45, Gilmeh Serda wrote:

On 2 Apr 2024 17:18:16 GMT, Stefan Ram wrote:


first_word_beginning_with_e


Here's another one:


def ret_first_eword():

... return [w for w in ['delta', 'epsilon', 'zeta', 'eta', 'theta'] if 
w.startswith('e')][0]
...

ret_first_eword()

'epsilon'


Doesn't work in the case where there isn't a word starting with 'e':

 >>> def find_e( l ):
 ...   return [w for w in l if w.startswith('e')][0]
 ...
 >>> l = ['delta', 'epsilon', 'zeta', 'eta', 'theta']
 >>> find_e(l)
 'epsilon'
 >>> l = ['The','fan-jet','airline']
 >>> find_e(l)
 Traceback (most recent call last):
   File "", line 1, in 
   File "", line 2, in find_e
 IndexError: list index out of range
 >>>


--
Michael F. Stemper
If it isn't running programs and it isn't fusing atoms, it's just bending space.

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


Re: Popping key causes dict derived from object to revert to object

2024-03-25 Thread Michael F. Stemper via Python-list

On 25/03/2024 01.56, Loris Bennett wrote:

Grant Edwards  writes:


On 2024-03-22, Loris Bennett via Python-list  wrote:


Yes, I was mistakenly thinking that the popping the element would
leave me with the dict minus the popped key-value pair.


It does.


Indeed, but I was thinking in the context of

   dict_list = [d.pop('a') for d in dict_list]

and incorrectly expecting to get a list of 'd' without key 'a', instead
of a list of the 'd['a]'.

I apologize if this has already been mentioned in this thread, but are
you aware of "d.keys()" and "d.values"?

 >>> d = {}
 >>> d['do'] = 'a deer, a female deer'
 >>> d['re'] = 'a drop of golden sunshine'
 >>> d['mi'] = 'a name I call myself'
 >>> d['fa'] = 'a long, long way to run'
 >>> d.keys()
 ['fa', 'mi', 'do', 're']
 >>> d.values()
 ['a long, long way to run', 'a name I call myself', 'a deer, a female deer', 
'a drop of golden sunshine']
 >>>


--
Michael F. Stemper
Exodus 22:21

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


Re: RE: Newline (NuBe Question)

2023-11-26 Thread Michael F. Stemper via Python-list

On 24/11/2023 21.45, avi.e.gr...@gmail.com wrote:

Grizz[l]y,

I think the point is not about a sorted list or sorting in general It is
about reasons why maintaining a data structure such as a list in a program
can be useful beyond printing things once. There are many possible examples
such as having a list of lists containing a record where the third item is a
GPA for the student and writing a little list comprehension that selects a
smaller list containing only students who are Magna Cum Laude or Summa Cum
Laude.

studs = [
   ["Peter", 82, 3.53],
   ["Paul", 77, 2.83],
   ["Mary", 103, 3.82]
]


I've seen Mary, and she didn't look like a "stud" to me.


Of course, for serious work, some might suggest avoiding constructs like a
list of lists and switch to using modules and data structures [...]


Those who would recommend that approach do not appear to include Mr.
Rossum, who said:
  
  Avoid overengineering data structures. Tuples are better than

  objects (try namedtuple too though). Prefer simple fields over
  getter/setter functions... Built-in datatypes are your friends.
  Use more numbers, strings, tuples, lists, sets, dicts. Also
  check out the collections library, eps. deque.[1]
  
I was nodding along with the people saying "list of lists" until I

reread this quote. A list of tuples seems most appropriate to me.

  
[1] <https://gist.github.com/hemanth/3715502>, as quoted by Bill

Lubanovic in _Introducing Python_

--
Michael F. Stemper
This sentence no verb.

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


Re: Question(s)

2023-10-25 Thread Michael F. Stemper via Python-list

On 25/10/2023 05.45, o1bigtenor wrote:

On Tue, Oct 24, 2023 at 8:35 PM Chris Angelico via Python-list
 wrote:



3. Catch the failure before you commit and push. Unit tests are great for this.


Where might I find such please.


You don't "find" unit tests; you write them. A unit test tests
a specific function or program.

Ideally, you write each unit test *before* you write the function
that it tests.

For instance, suppose that you were writing a function to calculate
the distance between two points. We know the following things about
distance:
1. The distance from a point to itself is zero.
2. The distance between two distinct points is positive.
3. The distance from A to B is equal to the distance from B to A.
4. The distance from A to B plus the distance from B to C is at
   least as large as the distance from A to C.

You would write unit tests that generate random points and apply
your distance function to them, checking that each of these
conditions is satisfied. You'd also write a few tests of hard-coded
points,such as:
- Distance from (0,0) to (0,y) is y
- Distance from (0,0) to (x,0) is x
- Distance from (0,0) to (3,4) is 5
- Distance from (0,0) to (12,5) is 13

The python ecosystem provides many tools to simplify writing and
running unit tests. Somebody has already mentioned "unittest". I
use this one all of the time. There are also "doctest", "nose",
"tox", and "py.test" (none of which I've used).

--
Michael F. Stemper
Life's too important to take seriously.

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


Re: Question(s)

2023-10-25 Thread Michael F. Stemper via Python-list

On 24/10/2023 18.15, o1bigtenor wrote:



What is interesting about this is the absolute certainty that it is impossible
to program so that that program is provably correct.


Not entirely true. If I was to write a program to calculate Fibonacci
numbers, or echo back user input, that program could be proven correct.
But, there is a huge set of programs for which it is not possible to
prove correctness.

In fact, there is a huge (countably infinite) set of programs for which it
is not even possible to prove that the program will halt.

Somebody already pointed you at a page discussing "The Halting Problem".
You really should read up on this.


Somehow - - - well - - to me that sounds that programming is illogical.

If I set up a set of mathematical problems (linked) I can prove that the
logic structure of my answer is correct.


Exactly the same situation. There are many (again, countably infinite)
mathematical statements where it is not possible to prove that the statement
is either true or false. I want to be clear that this is not the same as
"we haven't figured out how to do it yet." It is a case of "it is mathematically
possible to show that we can't either prove or disprove statement ."

Look up Kurt Gödel's work on mathematical incompleteness, and some of the
statements that fall into this category, such as the Continuum Hypothesis
or the Parallel Postulate.

As I said at the beginning, there are a lot of programs that can be
proven correct or incorrect. But, there are a lot more that cannot.

--
Michael F. Stemper
Outside of a dog, a book is man's best friend.
Inside of a dog, it's too dark to read.

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


Re: Question(s)

2023-10-25 Thread Michael F. Stemper via Python-list

On 24/10/2023 17.50, Thomas Passin wrote:



   The programming team for the Apollo moon mission developed a system which,> 
if you would write your requirements in a certain way, could generate correct
C code for them.

Since the last Apollo mission was in 1972, when C was first being developed, I
find this hard to believe.

--
Michael F. Stemper
Outside of a dog, a book is man's best friend.
Inside of a dog, it's too dark to read.

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


Re: error of opening Python

2023-09-26 Thread Michael F. Stemper via Python-list

On 26/09/2023 07.27, Abdelkhelk ashref salay eabakh wrote:

Dear Python team,

This is my not first time using Python, I tried to launch Python and it showed
"Python 3.11.3 (tags/v3.11.3:f3909b8, Apr  4 2023, 23:49:59) [MSC v.1934 64 bit 
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information." I
don't know what this meant and how to fix this. Could you please help me?


What error did you encounter? Aside from the lack of line breaks, it looks
quite similar to what I get when I start up python:

 Python 3.6.9 (default, Mar 10 2023, 16:46:00)
 [GCC 8.4.0] on linux
 Type "help", "copyright", "credits" or "license" for more information.
 >>>

Didn't you get the ">>> " prompt? Once you get it, it shows that the
Read, Evaluate, Print Loop (REPL) is ready for you to type some python
statements. For instance:

 >>> x = 2**3
 >>> print(x)
 8
 >>>

--
Michael F. Stemper
Outside of a dog, a book is man's best friend.
Inside of a dog, it's too dark to read.

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


Re: String to Float, without introducing errors

2022-12-19 Thread Michael F. Stemper

On 19/12/2022 09.14, MRAB wrote:

On 2022-12-19 14:10, Peter J. Holzer wrote:

On 2022-12-19 09:25:17 +1100, Chris Angelico wrote:

On Mon, 19 Dec 2022 at 07:57, Stefan Ram  wrote:
> G = Decimal( 6.6743015E-11 )
> r = Decimal( 6.371E6 )
> M = Decimal( 5.9722E24 )

What's the point of using Decimal if you start with nothing more than
float accuracy?


Right. He also interpreted the notation "6.67430(15)E-11" wrong. The
digits in parentheses represent the uncertainty in the same number of
last digits. So "6.67430(15)E-11" means "something between 6.67430E-11 -
0.00015E-11 and 6.67430E-11 + 0.00015E-11". The r value has only a
precision of 1 km and I'm not sure how accurate the mass is. Let's just
assume (for the sake of the argument) that these are actually accurate in
all given digits.


ntal misunderstanding of the numbers they are working with.



To be fair, I don't think I've never seen that notation either! I've only ever 
seen the form 6.67430E-11 ± 0.00015E-11, which is much clearer.


See, for instance:
<https://www.physics.nist.gov/cgi-bin/cuu/Value?bg>
In particular, the "concise form".

For more detail, see:
<https://en.wikipedia.org/wiki/Uncertainty#Measurements>

--
Michael F. Stemper
Isaiah 58:6-7
--
https://mail.python.org/mailman/listinfo/python-list


Re: Top level of a recursive function

2022-12-13 Thread Michael F. Stemper

On 13/12/2022 09.03, Stefan Ram wrote:

"Michael F. Stemper"  writes:

def fred(cf,toplevel=True):
   x = cf[0]
   if len(cf)>1:
 if toplevel:
   return x + fred(cf[1:],False)
 else:
   return "(" + x + fred(cf[1:],False) + ")"
   else:
 if toplevel:
   return x
 else:
   return "(" + x + ")"


def rest( s ):
 return "(" + s[ 0 ] +( rest( s[1:] ) if len( s )> 1 else '' )+ ')'

def nest( s ):
 return( s[ 0 ] if s else '' )+( rest( s[1:] )if len( s )> 1 else '' )


Hey, that's slick! And if I define rest within nest, it's not going
to be externally accessible.

Thanks

--
Michael F. Stemper
No animals were harmed in the composition of this message.
--
https://mail.python.org/mailman/listinfo/python-list


Top level of a recursive function

2022-12-13 Thread Michael F. Stemper

It's easy enough -- in fact necessary -- to handle the bottom
level of a function differently than the levels above it. What
about the case where you want to handle something differently
in the top level than in lower levels? Is there any way to tell
from within a function that it wasn't invoked by itself?

I've come up with a hack to support different processing, by
use of an extra argument, as shown in this simplified example:

def fred(cf,toplevel=True):
  x = cf[0]
  if len(cf)>1:
if toplevel:
  return x + fred(cf[1:],False)
else:
  return "(" + x + fred(cf[1:],False) + ")"
  else:
if toplevel:
  return x
else:
  return "(" + x + ")"

Aside from being ugly, this lets the caller diddle with "toplevel",
which shouldn't really be externally modifiable.

Are there better ways to do this?
--
Michael F. Stemper
I refuse to believe that a corporation is a person until Texas executes one.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Passing information between modules

2022-11-19 Thread Michael F. Stemper

On 18/11/2022 04.53, Stefan Ram wrote:

   Can I use "sys.argv" to pass information between modules
   as follows?

   in module A:

import sys
sys.argv.append( "Hi there!" )

   in module B:

import sys
message = sys.argv[ -1 ]


I just tried and it appears that one can append to sys.argv. However,
it seems like an incredibly bad idea.

--
Michael F. Stemper
The name of the story is "A Sound of Thunder".
It was written by Ray Bradbury. You're welcome.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Find the path of a shell command

2022-10-12 Thread Michael F. Stemper

On 12/10/2022 07.20, Chris Green wrote:

jak  wrote:

Il 12/10/2022 09:40, jkn ha scritto:

On Wednesday, October 12, 2022 at 6:12:23 AM UTC+1, jak wrote:



I'm afraid you will have to look for the command in every path listed in
the PATH environment variable.


erm, or try 'which rm' ?


You might but if you don't know where the 'rm' command is, you will have
the same difficulty in using 'which' command. Do not you think?

 From a command prompt use the bash built-in 'command' :-

 command -v rm

... and rm will just about always be in /usr/bin.


On two different versions of Ubuntu, it's in /bin.

--
Michael F. Stemper
Psalm 94:3-6
--
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-10 Thread Michael F. Stemper

On 09/10/2022 15.02, Peter J. Holzer wrote:

On 2022-10-09 15:32:13 -0400, Avi Gross wrote:

and of course no pipelines.


Since you've now used that term repeatedly: What is a pipeline in
Python?


Could it be what's discussed starting on page 35 of this presentation?
<http://www.dabeaz.com/generators/Generators.pdf>

--
Michael F. Stemper
Life's too important to take seriously.
--
https://mail.python.org/mailman/listinfo/python-list


Re: What to use for finding as many syntax errors as possible.

2022-10-10 Thread Michael F. Stemper

On 09/10/2022 10.49, Avi Gross wrote:

Anton

There likely are such programs out there but are there universal agreements
on how to figure out when a new safe zone of code starts where error
testing can begin?

For example a file full of function definitions might find an error in
function 1 and try to find the end of that function and resume checking the
next function.  But what if a function defines local functions within it?
What if the mistake in one line of code could still allow checking the next
line rather than skipping it all?

My guess is that finding 100 errors might turn out to be misleading. If you
fix just the first, many others would go away. If you spell a variable name
wrong when declaring it, a dozen uses of the right name may cause errors.
Should you fix the first or change all later ones?


How does one declare a variable in python? Sometimes it'd be nice to
be able to have declarations and any undeclared variable be flagged.

When I was writing F77 for a living, I'd (temporarily) put:
  IMPLICIT CHARACTER*3
at the beginning of a program or subroutine that I was modifying,
in order to have any typos flagged.

I'd love it if there was something similar that I could do in python.

--
Michael F. Stemper
87.3% of all statistics are made up by the person giving them.
--
https://mail.python.org/mailman/listinfo/python-list


Re: TkSheet

2022-10-08 Thread Michael F. Stemper

On 08/10/2022 07.58, Benny Rieger wrote:

What a great work;-)

I need a solution for save my tabel as csv. How to do that? Has someone a 
solution for that?


Is this what you're seeking?

<https://www.pythontutorial.net/python-basics/python-write-csv-file/>

--
Michael F. Stemper
No animals were harmed in the composition of this message.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Regarding python 3.10 installation

2022-09-19 Thread Michael F. Stemper

In order to save time for the experts here:

On 19/09/2022 00.51, Shadid Alam wrote:

Hello I’ve been trying to install updated python version i.e. python 10.7.


There is no python 10.7. Are you possibly trying to install python 3.10.7?

On what OS are you trying to install it?

How are you trying to install it?

Do you get any error messages when you try to install it?


Its showing installed but whenever I open python it comes up with the older


How are you "opening" it?


version i.e. 10.9 . Please fix this issue is possible


In order to do that, we'll need your root password and IP address.

--
Michael F. Stemper
Psalm 82:3-4
--
https://mail.python.org/mailman/listinfo/python-list


Re: Coffee

2022-08-30 Thread Michael F. Stemper

On 29/08/2022 07.16, Stefan Ram wrote:

|Python's obviously a great tool for all kinds of programming things,
|and I would say if you're only gonna use one programming
|language in your live, Python will probably the right one.
Brian Kernighan

   I transcribed this from the recent video
   "Coffee with Brian Kernighan".


For those who'd like to see the whole chat:
<https://www.youtube.com/watch?v=GNyQxXw_oMQ>

--
Michael F. Stemper
Deuteronomy 24:17
--
https://mail.python.org/mailman/listinfo/python-list


Re: random.SystemRandom().randint() inefficient

2022-07-27 Thread Michael F. Stemper

On 26/07/2022 16.47, Cecil Westerhof wrote:

Chris Angelico  writes:


On Wed, 27 Jul 2022 at 06:06, Cecil Westerhof via Python-list
 wrote:


Chris Angelico  writes:


On Wed, 27 Jul 2022 at 01:06, Cecil Westerhof via Python-list
 wrote:


I need to get a random integer. At first I tried it with:
 from secrets import randbelow
 index = randbelow(len(to_try))

This works perfectly, but it took some time. So I thought I try:
 from random  import SystemRandom
 index = SystemRandom().randint(0, len(to_try) - 1)

A first indication is that the second version would take about two
times as much time as the first. Is there a reason for this, or should
this not be happening?



You're setting up a brand new SystemRandom instance just for a single
random number. For a fairer comparison, set up the instance, then
generate far more than just a single number, and see how that goes.


Thanks. I thought I did something wrong and I did.
I will try to implement like you said and look what the result will
be. (And share it.)


Thanks! Don't feel bad; performance testing is *hard*, getting
meaningful results takes a lot of of fiddling with parameters, and
getting interesting AND meaningful results can sometimes seem about
impossible.


(As I understand it both do more, or less the same and should have
comparable performance.)


In normal production work? Yes (the SystemRandom object doesn't have
any significant state - a seeded RNG could have a lot more overhead
here). But for performance testing? The work of instantiating the
class could be completely irrelevant, or it could be dominating your
results. It's hard to say, hence the suggestion to try it without
reinstantiating.


It had a very big influence. Original it took about three times more
time to run my program. (The program was still running when I posted
the original post and the difference was higher as I anticipated.)
Removing that did cut about 45% of the execution time of the program.
(So the initiation is quit expensive.)
But it still takes about 50% more time. So I am still a bit
flabbergasted.

The new code:
 from random  import SystemRandom
 system_random   = SystemRandom()
 index = system_random.randint(0, len(to_try) - 1)


This is orthogonal to your question, but might be of some use to you:

The combination of using len(to_try) as an argument to randint() and
saving the output to a variable named "index" suggests that you might
be setting up to select a random element from to_try, as in:
  something = to_try[index]

If that is the case, you might want to consider using random.choice() instead:

  >>> from random import choice
  >>> to_try = [2,3,5,7,11,13,"seventeen",19]
  >>> choice(to_try)
  2
  >>> choice(to_try)
  'seventeen'
  >>> choice(to_try)
  13
  >>> choice(to_try)
  5
  >>>

--
Michael F. Stemper
This sentence no verb.
--
https://mail.python.org/mailman/listinfo/python-list


Re: calculate diff between dates

2022-07-14 Thread Michael F. Stemper

On 12/07/2022 07.37, נתי שטרן wrote:

[snip ugly code that I'm not going to try to understand]



I glad for any help


There wasn't any question in your post. However, I'm going to
guess that there was the implied question of "How does one
find the difference between two dates?"


 >>> import datetime
 >>> d1 = datetime.date(2022,1,1)
 >>> d2 = datetime.date(2022,7,12)
 >>> d2-d1
 datetime.timedelta(192)
 >>>


--
Michael F. Stemper
If it isn't running programs and it isn't fusing atoms, it's just bending space.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Why isn't there a built-in product()?

2022-07-09 Thread Michael F. Stemper

On 07/07/2022 19.06, Oscar Benjamin wrote:

On Thu, 7 Jul 2022 at 22:55, Michael F. Stemper
 wrote:


sum() is wonderful.



I understand that there is no product() or prod(). Does anybody
here know why that was not included in the language? It seems
as if it would be useful, so there must have been some rationale
for that decision.


There is math.prod:

   >>> from math import prod
   >>> prod([1, 2, 3, 4])
   24

https://docs.python.org/3/library/math.html#math.prod


I did not know that. Thanks.


--
Michael F. Stemper
Outside of a dog, a book is man's best friend.
Inside of a dog, it's too dark to read.
--
https://mail.python.org/mailman/listinfo/python-list


Why isn't there a built-in product()?

2022-07-07 Thread Michael F. Stemper

sum() is wonderful.

 >>> nums = [1,2,3]
 >>> sum(nums)
 6
 >>> product(nums)
 Traceback (most recent call last):
   File "", line 1, in 
 NameError: name 'product' is not defined
 >>>

I understand that there is no product() or prod(). Does anybody
here know why that was not included in the language? It seems
as if it would be useful, so there must have been some rationale
for that decision.

--
Michael F. Stemper
87.3% of all statistics are made up by the person giving them.
--
https://mail.python.org/mailman/listinfo/python-list


Re: fill out bulletins

2022-06-13 Thread Michael F. Stemper

On 13/06/2022 08.49, jak wrote:

Hello everyone,
I would like to write a tool to compile post office bulletins because
here, unfortunately, they are still the most convenient way to interface
the public administration. I don't want to create a UI to edit the
bulletin, I will take the data from some file or database but I'd like
to print or save the bulletin to the file with all the fields filled in.
To accomplish this, I thought about creating a basic graphic (jpg?) file
with the bulletin image,


Please don't create an image. Create something that preserves
text as text, so that your recipients can (if they so desire)
search on that text, or copy/paste from your bulletin.

Somebody suggested TeX/LaTeX. Excellent idea.

--
Michael F. Stemper
A preposition is something you should never end a sentence with.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Function to Print a nicely formatted Dictionary or List?

2022-06-09 Thread Michael F. Stemper

On 09/06/2022 12.52, Chris Angelico wrote:

On Fri, 10 Jun 2022 at 03:44, Dave  wrote:



Before I write my own I wondering if anyone knows of a function that will print 
a nicely formatted dictionary?

By nicely formatted I mean not all on one line!



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

from pprint import pprint
pprint(thing)


 >>> from pprint import pprint
 >>> d = {'two':2, 'three':5}
 >>> pprint(d)
 {'three': 5, 'two': 2}
 >>>

This is all on one line. That might be acceptable to the OP, but it
doesn't actually match what he said.

--
Michael F. Stemper
Outside of a dog, a book is man's best friend.
Inside of a dog, it's too dark to read.
--
https://mail.python.org/mailman/listinfo/python-list


Re: min, max with position

2022-06-05 Thread Michael F. Stemper

On 04/06/2022 14.08, Stefan Ram wrote:

"Michael F. Stemper"  writes:

Are there similar functions that return not only the minimum
or maximum value, but also its position?


   The maximum value does not need to have a unique position.


Which is something that I'll just have to live with, whether I
use home-brew or something from a standard module. For the particular
application, my lists have 24 elements and are converted from data
that is received in a %5.2f format, so collisions aren't too likely
anyway.


   The World-Wide Web holds several suggestions like l.index(
   max( l )) or max( enumerate( l ), key=( lambda x: x[ 1 ])).


Oh, I like that second one. I tried playing around with a lambda
function, but combining with enumerate eluded me. It's much better
than my for-loop with extraneous variables.

--
Michael F. Stemper
Psalm 94:3-6
--
https://mail.python.org/mailman/listinfo/python-list


Re: min, max with position

2022-06-04 Thread Michael F. Stemper

On 04/06/2022 13.56, Dennis Lee Bieber wrote:

On Sat, 4 Jun 2022 13:36:26 -0500, "Michael F. Stemper"
 declaimed the following:



Are there similar functions that return not only the minimum
or maximum value, but also its position?


If it isn't in the library reference manual, NO...

But it also isn't that difficult to write...


I already wrote it. I was wondering if there was something
standard that I should have used instead. I have multiple
functions that I wrote, only to later learn that there were
standard functions that did the same thing.

--
Michael F. Stemper
This email is to be read by its intended recipient only. Any other party
reading is required by the EULA to send me $500.00.
--
https://mail.python.org/mailman/listinfo/python-list


min, max with position

2022-06-04 Thread Michael F. Stemper

Python contains built-in functions that return the minimum or
maximum items in a list.

 >>> l = [1.618033,3.141593,2.718282]
 >>> min(l)
 1.618033
 >>> max(l)
 3.141593
 >>>

Are there similar functions that return not only the minimum
or maximum value, but also its position?

 >>> specialmin(l)
 (0,1.618033)
 >>> specialmax(l)
 3.141593
 >>>

--
Michael F. Stemper
I feel more like I do now than I did when I came in.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Automatic Gain Control in Python?

2022-05-29 Thread Michael F. Stemper

On 29/05/2022 10.04, Steve GS wrote:


What you seem to be missing is that you could get the podcasts from a browser, 
and all a browser is is a program. It isn't that much work to write a 
rudimentary browser in python, especially if you don't actually need to display 
the results to a user, but are only trying to automate a particular task.


Writing my own browser in Python might work. Do you have a sample one that I 
could twerk to fit my needs?
I would have to be able to invoke it and an hour later devoke it least I end up 
with multiple audio channels playing.


Somebody has already shown the rudiments of urllib. Another option to consider
is the use of something like curl or wget to download the podcasts, which can
be automated separately from your replay program.

--
Michael F. Stemper
This email is to be read by its intended recipient only. Any other party
reading is required by the EULA to send me $500.00.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Changing calling sequence

2022-05-12 Thread Michael F. Stemper

On 11/05/2022 14.58, anthony.flury wrote:


Why not do :

   def TempsOneDayDT(date:datetime.date):
  return TempsOneDay(date.year, date.month, date.day)

No repeat of code - just a different interface to the same functionality.


Yeah, a one-line wrapper around the original function seems a
lot simpler that any of my ideas. I think that I'll even use the
name from your example.

Thanks to all who posted, as well as the many lurkers who support me
in email.


--
Michael F. Stemper
Economists have correctly predicted seven of the last three recessions.
--
https://mail.python.org/mailman/listinfo/python-list


Changing calling sequence

2022-05-11 Thread Michael F. Stemper

I have a function that I use to retrieve daily data from a
home-brew database. Its calling sequence is;

def TempsOneDay( year, month, date ):

After using it (and its friends) for a few years, I've come to
realize that there are times where it would be advantageous to
invoke it with a datetime.date as its single argument.

As far as I can tell, there are three ways for me to proceed:
1. Write a similar function that takes a single datetime.date
   as its argument.
2. Rewrite the existing function so that it takes a single
   argument, which can be either a tuple of (year,month,date)
   or a datetime.date argument.
3. Rewrite the existing function so that its first argument
   can be either an int (for year) or a datetime.date. The
   existing month and date arguments would be optional, with
   default=None. But, if the first argument is an int, and
   either of month or date is None, an error would be raised.

The first would be the simplest. However, it is obviously WET
rather than DRY.

The second isn't too bad, but a change like this would require that
I find all places that the function is currently used and insert a
pair of parentheses. Touching this much code is risky, as well
as being a bunch of work. (Admittedly, I'd only do it once.)

The third is really klunky, but wouldn't need to touch anything
besides this function.

What are others' thoughts? Which of the approaches above looks
least undesirable (and why)? Can anybody see a fourth approach?

--
Michael F. Stemper
This post contains greater than 95% post-consumer bytes by weight.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Style for docstring

2022-04-24 Thread Michael F. Stemper

On 24/04/2022 08.24, Michael F. Stemper wrote:

On 23/04/2022 12.43, Avi Gross wrote:

Given what you added, Michael, your function is part of a larger collection of 
functions and being compatible with the others is a valid consideration. 
Whatever you decide, would ideally be done consistently with all or most of 
them.
And, of course, it others in the collection also can handle multiple ways to 
specify a permutation, it may be simpler to have each call something like 
as.permutation() that handlesmultiple forms and converts to the one easiest for 
you to use.
I am not sure that is needed as I suspect the simplest storage is something 
like a list:  [0,3,2,4,5,6,7,1,9,8] but could also be shown with each cycle as 
a sub-list or something like anumpy vector or a customized class.


Since you ask, I'm using dictionaries as the internal representation.
If you think about it, a python dictionary *is* a function from one
finite set to another, mathematically. And a (finite) permutation is
a bijection from a (finite) set to itself.

For convenience, the module provides two methods of defining a permutation
other than just entering a dictionary:

  >>> import PermGroups as pg
  >>> a = {'1':'2', '2':'1', '3':'3'}
  >>> b = pg.ParsePerm( '(12)(3)' )
  >>> c = pg.ParseDomImg( '123', '213' )
  >>> a==b
  True
  >>> b==c
  True
  >>>

All of the other functions work on these dictionaries.

I had thought about defining a permutation object, but the conceptual
match between "dict" and "permutation" was too good to discard.


Clearly if you control the package and how it is used, errors from bad data may 
not be a concern.


An invalidly-constructed permutation will cause an exception, so
the function won't return.


The below was *not* intended to illustrate what I said above. It
shows the validation function provided by the module. This allows
the user to avoid the consequences of an invalidly-constructed
permutation. (It's only for users who don't subscribe to "EAFP",
of course.)


  >>> d = {'1':'2', '2':'2', '3':'3'}
  >>> pg.ValidateDict(d)
  False
  >>>

If I was to do it over, I would have named this function something
like IsValidPermutation(), hiding the internal representation as
well as making the function's Boolean nature explicit.




--
Michael F. Stemper
Psalm 82:3-4
--
https://mail.python.org/mailman/listinfo/python-list


Re: Style for docstring

2022-04-24 Thread Michael F. Stemper

On 23/04/2022 12.43, Avi Gross wrote:

Given what you added, Michael, your function is part of a larger collection of 
functions and being compatible with the others is a valid consideration. 
Whatever you decide, would ideally be done consistently with all or most of 
them.
And, of course, it others in the collection also can handle multiple ways to 
specify a permutation, it may be simpler to have each call something like 
as.permutation() that handlesmultiple forms and converts to the one easiest for 
you to use.
I am not sure that is needed as I suspect the simplest storage is something 
like a list:  [0,3,2,4,5,6,7,1,9,8] but could also be shown with each cycle as 
a sub-list or something like anumpy vector or a customized class.


Since you ask, I'm using dictionaries as the internal representation.
If you think about it, a python dictionary *is* a function from one
finite set to another, mathematically. And a (finite) permutation is
a bijection from a (finite) set to itself.

For convenience, the module provides two methods of defining a permutation
other than just entering a dictionary:

 >>> import PermGroups as pg
 >>> a = {'1':'2', '2':'1', '3':'3'}
 >>> b = pg.ParsePerm( '(12)(3)' )
 >>> c = pg.ParseDomImg( '123', '213' )
 >>> a==b
 True
 >>> b==c
 True
 >>>

All of the other functions work on these dictionaries.

I had thought about defining a permutation object, but the conceptual
match between "dict" and "permutation" was too good to discard.


Clearly if you control the package and how it is used, errors from bad data may 
not be a concern.


An invalidly-constructed permutation will cause an exception, so
the function won't return.

 >>> d = {'1':'2', '2':'2', '3':'3'}
 >>> pg.ValidateDict(d)
 False
 >>>

If I was to do it over, I would have named this function something
like IsValidPermutation(), hiding the internal representation as
well as making the function's Boolean nature explicit.

--
Michael F. Stemper
No animals were harmed in the composition of this message.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Style for docstring

2022-04-23 Thread Michael F. Stemper

On 22/04/2022 16.12, alister wrote:

On Fri, 22 Apr 2022 14:36:27 -0500, Michael F. Stemper wrote:


I'm writing a function that is nearly self-documenting by its name,
but still want to give it a docstring. Which of these would be best from
a stylistic point of view:




for guidance I would sugest Pep257 as a start point
which would suggest "Return True if permutation is even"


I'll take a look at the PEP. Thanks.


--
Michael F. Stemper
This email is to be read by its intended recipient only. Any other party
reading is required by the EULA to send me $500.00.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Style for docstring

2022-04-23 Thread Michael F. Stemper

On 22/04/2022 21.58, Avi Gross wrote:

Python does have a concept of "truthy" that includes meaning for not just the 
standard Booleans but for 0 and non-zero and the empty string and many more odd things 
such as an object that defines __bool__ ().
But saying it returns a Boolean True/False valuesounds direct and simple and 
informative enough if that is True.
What bothers me is the assumption that anyone knows not so muchjust group 
theory  but what the argument to the function looks like as a Python object of 
some kind.
Does the function accept only some permutation object managed by a specific 
module? Will it accept some alternate representation such as a list structure 
or other iterator?


That's a fair point. However, this function will be the 22nd one in
a module for dealing with permutations and groups of permutations.
The module has a lengthy docstring explaining the several ways provided
to specify a permutation. That way, the same information doesn't need
to be written twenty-plus times.


Obviously deeper details would normally be in a manual page or other documentation but as 
"permutations" are likely not to be what most people think about before 
breakfast, or even  after, odd as that may seem, ...


I see what you did there :->

--
Michael F. Stemper
Psalm 94:3-6
--
https://mail.python.org/mailman/listinfo/python-list


Re: Style for docstring

2022-04-22 Thread Michael F. Stemper

On 22/04/2022 14.59, Chris Angelico wrote:

On Sat, 23 Apr 2022 at 05:56, Michael F. Stemper
 wrote:


I'm writing a function that is nearly self-documenting by its name,
but still want to give it a docstring. Which of these would be
best from a stylistic point of view:


Tells caller whether or not a permutation is even.

Determines if a permutation is even. (Alternative is that it's odd.)

Returns True if permutation is even, False if it is odd.





I'd go with the third one, but "Return" rather than "Returns". Or
possibly "Test whether a permutation is even".


"So let it be written. So let it be done."


That's just one opinion though, others may disagree :)


Two for two. Thanks.


--
Michael F. Stemper
Always remember that you are unique. Just like everyone else.
--
https://mail.python.org/mailman/listinfo/python-list


Style for docstring

2022-04-22 Thread Michael F. Stemper

I'm writing a function that is nearly self-documenting by its name,
but still want to give it a docstring. Which of these would be
best from a stylistic point of view:


  Tells caller whether or not a permutation is even.

  Determines if a permutation is even. (Alternative is that it's odd.)

  Returns True if permutation is even, False if it is odd.


(Before somebody suggests it, I'm not going to put six weeks' worth
of a course in group theory in there to help somebody who doesn't
know what those standard terms mean.)

--
Michael F. Stemper
87.3% of all statistics are made up by the person giving them.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Feature Request

2022-03-23 Thread Michael F. Stemper

On 23/03/2022 03.55, Kazuya Ito wrote:

Add "trun()" function to Python to truncate decimal part.


Which of these should its behavior copy?


from math import pi
int(pi)

3

pi-int(pi)

0.14159265358979312




--
Michael F. Stemper
This post contains greater than 95% post-consumer bytes by weight.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Behavior of the for-else construct

2022-03-05 Thread Michael F. Stemper

On 04/03/2022 18.11, Peter J. Holzer wrote:

On 2022-03-04 23:47:09 +, Avi Gross via Python-list wrote:

I am not sure a reply is needed, Peter, and what you say is true. But
as you point out, when using a German keyboard, I would  already have
a way to enter symbols like ä, ö, ü and ß and no reason not to include
them in variable names and so on if UNICODE is being used properly. I
can use my last name in German notation as a variable in Python now:

Groß = 144
Groß / 12
12.0


Yes, I'm using umlauts occasionally in variable names in Python, and
I've also used Greek characters and others.

But in Python I CAN use them. I DON'T HAVE to.

That's a big difference.

Characters like [] or {} are a part of Python's syntax. You can't avoid
using them. If you can't type them, you can't write Python. If it is
awkward to enter them (like having to type Alt-91 or pasting them from a
character table) it is painful to write programs.

German keyboards aquired an AltGr key and the ability to type these
characters in the mid to late 1980's. Presumably because those
characters were common in C and other programming languages


... especially Pascal, which was probably bigger in Germany and Austria
in the 1980s than was C.

--
Michael F. Stemper
Psalm 94:3-6
--
https://mail.python.org/mailman/listinfo/python-list


Re: Behavior of the for-else construct

2022-03-04 Thread Michael F. Stemper

On 03/03/2022 19.54, Rob Cliffe wrote:

On 04/03/2022 01:44, Ethan Furman wrote:

On 3/3/22 5:32 PM, Rob Cliffe via Python-list wrote:

> There are three types of programmer: those that can count, and those that 
can't.

Actually, there are 10 types of programmer:  those that can count in binary, 
and those that can't.

1, 10, many.
No problem.


Ah, a George Gamow fan.

--
Michael F. Stemper
Psalm 82:3-4
--
https://mail.python.org/mailman/listinfo/python-list


Re: Behavior of the for-else construct

2022-03-03 Thread Michael F. Stemper

On 03/03/2022 07.24, computermaster360 wrote:

I want to make a little survey here.

Do you find the for-else construct useful? Have you used it in
practice? Do you even know how it works, or that there is such a thing
in Python?


I only found out about it within the last year or so. I've used it
probably half-a-dozen times. It seems quite elegant to me.


--
Michael F. Stemper
A preposition is something you should never end a sentence with.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Best way to check if there is internet?

2022-02-25 Thread Michael F. Stemper

On 25/02/2022 14.30, 2qdxy4rzwzuui...@potatochowder.com wrote:

On 2022-02-25 at 13:48:32 -0600,
"Michael F. Stemper"  wrote:


On 25/02/2022 12.07, Abdur-Rahmaan Janhangeer wrote:



I have been following language feature proposals from various
languages. Some decide to avoid Python's route, but others have been
trying hard to catch up with Python.  One gleaming example is the
switch case. JS recently proposed pattern matching, referencing
Python and explaining why the proposal is a cool treatment of the
usecase.



I'm not clear on what you mean here. JavaScript has had a switch/case
construct since 1.2, in the late 1990s. As far as I can determine,
python has no such thing, since PEP-3103 was rejected in 2007.


Python has a relatively new (as of version 3.10) "match" statement:

 https://docs.python.org/3/reference/compound_stmts.html#the-match-statement


Looks as if I have some reading to do. Thanks.


--
Michael F. Stemper
Always use apostrophe's and "quotation marks" properly.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Best way to check if there is internet?

2022-02-25 Thread Michael F. Stemper

On 25/02/2022 12.07, Abdur-Rahmaan Janhangeer wrote:


I have been following language feature proposals from various
languages. Some decide to avoid Python's route,
but others have been trying hard to catch up with Python.
One gleaming example is the switch case. JS recently proposed pattern
matching, referencing Python and explaining why the proposal
is a cool treatment of the usecase.


I'm not clear on what you mean here. JavaScript has had a
switch/case construct since 1.2, in the late 1990s. As far
as I can determine, python has no such thing, since PEP-3103
was rejected in 2007.


As a side note, if by scripting we mean OS commands,
then Python started as a sysadmin language.


I never knew this. Where can I read more about this origin?

--
Michael F. Stemper
If it isn't running programs and it isn't fusing atoms, it's just bending space.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Best way to check if there is internet?

2022-02-25 Thread Michael F. Stemper

On 25/02/2022 06.49, Abdur-Rahmaan Janhangeer wrote:


Thanks for the in-between. I really like the Python comunity as,
even though it's a 'scripting' language,


To me, it's a programming language. In my usage, a "script" is
a bunch of OS commands.

--
Michael F. Stemper
Life's too important to take seriously.
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-29 Thread Michael F. Stemper

On 28/09/2021 18.21, Greg Ewing wrote:

On 29/09/21 4:37 am, Michael F. Stemper wrote:

I'm talking about something made
from tons of iron and copper that is oil-filled and rotates at 1800 rpm.


To avoid confusion, we should rename them "electricity comprehensions".


Hah!

--
Michael F. Stemper
If you take cranberries and stew them like applesauce they taste much
more like prunes than rhubarb does.
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-28 Thread Michael F. Stemper

On 28/09/2021 13.27, Avi Gross wrote:

Well, Michael, if you want to go back to the eighties, and people you worked
with, I did my Thesis with a professor who later had an Erdős number of 1!
Too bad I never got around to publishing something with him or I could have
been a 2!


Lucky you. If a paper that a friend of mine is submitting to various
journals gets accepted by one of them, I'll end up with a 4 or 5 through
him. However, as the months pass, it's looking more like mine will end
up NaN.

--
Michael F. Stemper
Isaiah 58:6-7
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-28 Thread Michael F. Stemper

On 28/09/2021 10.53, Stefan Ram wrote:

"Michael F. Stemper"  writes:

Well, I could continue to hard-code the data into one of the test
programs


   One can employ a gradual path from a program with hardcoded
   data to an entity sharable by different programs.

   When I am hurried to rush to a working program, I often
   end up with code that contains configuration data spread
   (interspersed) all over the code. For example:



   1st step: give a name to all the config data:



   2nd: move all config data to the top of the source code,
   directly after all the import statements:



   3rd: move all config data to a separate "config.py" module:

import ...
import config
...

...
open( config.project_directory + "data.txt" )
...


but that would mean that every time that I wanted to look
at a different scenario, I'd need to modify a program.


   Now you just have to modify "config.py" - clearly separated
   from the (rest of the) "program".


Well, that doesn't really address what format to store the data
in. I was going to write a module that would read data from an
XML file:

import EDXML
gens = EDXML.GeneratorsFromXML( "gendata1.xml" )
fuels = EDXML.FuelsFromXML( "fueldata3.xml" )

(Of course, I'd really get the file names from command-line arguments.)

Then I read a web page that suggested use of XML was a poor idea,
so I posted here asking for a clarification and alternate suggestions.

One suggestion was that I use YAML, in which case, I'd write:

import EDfromYAML
gens = EDfromYAML( "gendata1.yaml" )
fuels = EDXML.FuelsFromYAML( "fueldata3.yaml" )


And when I discover anomalous behavior, I'd need to copy the
hard-coded data into another program.


   Now you just have to import "config.py" from the other program.


This sounds like a suggestion that I hard-code the data into a
module. I suppose that I could have half-a-dozen modules with
different data sets and ln them as required:

$ rm GenData.py* FuelData.py*
$ ln gendata1.py GenData.py
$ ln fueldata3.py FuelData.py

It seems to me that a more thorough separation of code and data
might be useful.

--
Michael F. Stemper
The name of the story is "A Sound of Thunder".
It was written by Ray Bradbury. You're welcome.
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-28 Thread Michael F. Stemper

On 28/09/2021 02.25, Peter J. Holzer wrote:

On 2021-09-27 21:01:04 -0400, Avi Gross via Python-list wrote:

You keep talking about generators, though. If the generators are outside of
your program, then yes, you need to read in whatever they produce.


As I understood it, the "generators" don't generate the data, they are
the subject of the data: Devices that generate electricity by burning
fuel and he's modelling some aspect of their operation. Maybe efficiency
or power output or something like that (I tried to search for "IHR
curve", but couldn't find anything).


If you expand "IHR curve" to "incremental heat rate curve", you'll get
better results. When power engineers talk, we say the first, when we
publish papers, we write the second.

If you want to see the bigger picture, search on "Economic Dispatch".
In fact, doing so points me to something written by a guy I worked with
back in the 1980s:
<http://www2.econ.iastate.edu/classes/econ458/tesfatsion/EconomicDispatchIntroToOptimization.DKirschen2004.LTEdits.pdf>

Slide 3 even shows a piecewise-linear curve.

--
Michael F. Stemper
A preposition is something you should never end a sentence with.
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-28 Thread Michael F. Stemper

On 27/09/2021 20.01, Avi Gross wrote:

Michael,

Given your further explanation, indeed reading varying numbers of points in
using a CSV is not valid, albeit someone might just make N columns (maybe a
few more than 7) to handle a hopefully worst case. Definitely it makes more
sense to read in a list or other data structure.

You keep talking about generators, though. If the generators are outside of
your program, then yes, you need to read in whatever they produce.


My original post (which is as the snows of yesteryear) made explicit the
fact that when I refer to a generator, I'm talking about something made
from tons of iron and copper that is oil-filled and rotates at 1800 rpm.
(In most of the world other than North America, they rotate at 1500 rpm.)

Nothing to do with the similarly-named python construct. Sorry for the
ambiguity.


But if
your data generator is within your own program,


The data is created in my mind, and approximates typical physical
characteristics of real generators.


My impression is you may not be using your set of data points for any other
purposes except when ready to draw a spline.


Nope, the points give a piecewise-linear curve, and values between two
consecutive points are found by linear interpolation. It's industry
standard practice.



Can I just ask if by a generator, you do NOT mean the more typical use of
"generator" as used in python


Nope; I mean something that weighs 500 tons and rotates, producing
electrical energy.


  Do you mean something that creates
realistic test cases to simulate a real-word scenario?


The thing that creates realistic test cases is my brain.


  These often can
create everything at once and often based on random numbers.


I have written such, but not in the last thirty years. At that time, I
needed to make up data for fifty or one hundred generators, along with
tie lines and loads.

What I'm working on now only needs a handful of generators at a time;
just enough to test my hypothesis. (Theoretically, I could get by with
two, but that offends my engineering sensibilities.)


create everything at once and often based on random numbers. Again, if you
have or build such code, it is not clear it needs to be written to disk and
then read back.


Well, I could continue to hard-code the data into one of the test
programs, but that would mean that every time that I wanted to look
at a different scenario, I'd need to modify a program. And when I
discover anomalous behavior, I'd need to copy the hard-coded data
into another program.

Having the data in a separate file means that I can provide a function
to read that file and return a list of generators (or fuels) to a
program. Multiple test cases are then just multiple files, all of which
are available to multiple programs.


  You may of course want to save it, perhaps as a log, to show
what your program was working on.


That's another benefit of having the data in external files.

--
Michael F. Stemper
A preposition is something you should never end a sentence with.
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-27 Thread Michael F. Stemper

On 25/09/2021 16.48, 2qdxy4rzwzuui...@potatochowder.com wrote:

On 2021-09-25 at 15:20:19 -0500,
"Michael F. Stemper"  wrote:


... For instance, if
I modeled a fuel like this:

   
 ton
 21.96
 18.2
   

and a generating unit like this:

   
 
   
   
   
   
 
 
   
   
   
   
 
   

why would the fact that I could have chosen, instead, to model
the unit of measure as an attribute of the fuel, or its name
as a sub-element matter? Once the modeling decision has been
made, all of the decisions that might have been would seem to
be irrelevant.


Disclaimer:  I am not a big XML fan, for a number of reasons
already stated in this thread.

That said, please do include units in elements like heat_content,
whether or not it's Joules/kilogram/K, and price, even if is the
local currency in the only country to which your data applies.


Since the units (dimensions) don't matter as long as they're consistent
between heat_content and the IHR value (MBTU and MBTU/MWh or GJ and
GJ/MWh), I was initially going to ignore this suggestion. However, it
seems that if I added attributes for the unit of measure of heat, that
would allow checking that the data provided are indeed consistent.

Thanks for the suggestion.

With respect to currency, I've had customers (back when I had to work
for a living) use dollars, pesetas, Euros, and pounds. In of Wood and
Wollenberg[1], the authors use \cancel{R} to represent a generic
currency. But I might even add a currency attribute to the price
element.


If there's a standard for your industry, or your company, or on
some other level, then at least document what it is and that
you're using it, so that the next person (which may be you a
year from now) doesn't have to guess.


As far as power is concerned, this is utility-level generating fleets,
so it's always going to be MW -- even in the US, where we still use
BTUs for heat.



[1] _Power Generation, Operation, and Control; Allen J. Wood and Bruce
F. Wollenberg; (c) 1984, John Wiley & Sons.
--
Michael F. Stemper
The FAQ for rec.arts.sf.written is at
<http://leepers.us/evelyn/faqs/sf-written.htm>
Please read it before posting.
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-27 Thread Michael F. Stemper

On 25/09/2021 16.39, Avi Gross wrote:

Michael,

I don't care what you choose. Whatever works is fine for an internal use.


Maybe I should have taken the provoking article with a few more grains
of salt. At this point, I'm not seeing any issues that are applicable to
my use case.


But is the data scheme you share representative of your actual application?


From what I see below, unless the number of "point" variables is not always

exactly four, the application might be handled well by any format that
handles rectangular data, perhaps even CSV.

You show a I mean anything like a data.frame can contain data columns like
p1,p2,p3,p4 and a categorical one like IHRcurve_name.

Or do you have a need for more variability such as an undetermined number of
similar units in ways that might require more flexibility or be more
efficient done another way?


As far as the number of points per IHR curve, the only requirement
is that there must be at least two. It's hard to define a line segment
with only one. The mock data that I have so far has curves ranging
from two to five points. I didn't notice that the snippet that I
posted had two curves with the same number of breakpoints, which was
misleading.

My former employer's systems had, IIRC, space for seven points per curve
in the database structures. Of all the sizing changes made over a long
career, I don't recall any customer ever requiring more than that. But,
it's cleanest to use python lists (with no inherent sizing limitations)
to represent the IHR (and incremental cost) curves.



MOST of the discussion I am seeing here seems peripheral to getting you what
you need for your situation and may require a learning curve to learn to use
properly. Are you planning on worrying about how to ship your data
encrypted, for example? Any file format you use for storage can presumably
be encrypted and send and decrypted if that matters.


This work is intended to look at the feasability of relaxing some
constraints normally required for the solution of Economic Dispatch.
So all of my data are hypothetical. Once I have stuff up and running,
I'll be making up data for lots of different generators.

Being retired, I don't have access to any proprietary information
about any specific generators, so all of the data is made up out
of my head. I still need a way to get it into my programs, of course.


So, yes, from an abstract standpoint we can discuss the merits of various
approaches. If it matters that humans can deal with your data in a file or
that it be able to be imported into a program like EXCEL, those are
considerations. But if not, there are quite a few relatively binary formats
where your program can save a snapshot of the data into a file and read it
back in next time.


Not needed here. I'm strictly interested in getting the models of
(generic) generating fleets in. Output of significant results will
probably be in CSV, which nicely replicates tabular displays that
I used through most of my career.


Or, did I miss something and others have already produced the data using
other tools, in which case you have to read it in at least once/


Well, the "tool" is vi, but this is a good description of what I'm
doing.

--
Michael F. Stemper
The FAQ for rec.arts.sf.written is at
<http://leepers.us/evelyn/faqs/sf-written.htm>
Please read it before posting.
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-25 Thread Michael F. Stemper

On 21/09/2021 13.12, Michael F. Stemper wrote:


If XML is not the way to package data, what is the recommended
approach?


Well, there have been a lot of ideas put forth on this thread,
many more than I expected. I'd like to thank everyone who
took the time to contribute.

Most of the reasons given for avoiding XML appear to be along
the lines of "XML has all of these different options that it
supports."

However, it seems that I could ignore 99% of those things and
just use a teeny subset of its capabilities. For instance, if
I modeled a fuel like this:

  
ton
21.96
18.2
  

and a generating unit like this:

  

  
  
  
  


  
  
  
  

  

why would the fact that I could have chosen, instead, to model
the unit of measure as an attribute of the fuel, or its name
as a sub-element matter? Once the modeling decision has been
made, all of the decisions that might have been would seem to
be irrelevant.

Some years back, IEC's TC57 came up with CIM[1]. This nailed down
a lot of decisions. The fact that other decisions could have been
made doesn't seem to keep utilities from going forward with it as
an enterprise-wide data model.

My current interests are not anywhere so expansive, but it seems
that the situations are at least similar:
1. Look at an endless range of options for a data model.
2. Pick one.
3. Run with it.

To clearly state my (revised) question:

  Why does the existence of XML's many options cause a problem
  for my use case?


Other reactions:

Somebody pointed out that some approaches would require that I
climb a learning curve. That's appreciated, although learning
new things is always good.

NestedText looks cool, and a lot like YAML. Having not gotten
around to playing with YAML yet, I was surprised to learn that it
tries to guess data types. This sounds as if it could lead to the
same type of problems that led to the names of some genes being
turned into dates.

It was suggested that I use an RDBMS, such as sqlite3, for the
input data. I've used sqlite3 for real-time data exchange between
concurrently-running programs. However, I don't see syntax like:

sqlite> INSERT INTO Fuels
   ...> (name,uom,price,heat_content)
   ...> VALUES ("Montana Sub-Bituminous", "ton", 21.96, 13.65);

as being nearly as readable as the XML that I've sketched above.
Yeah, I could write a program to do this, but that doesn't really
change anything, since I'd still need to get the data into the
program.

(Changing a value would be even worse, requiring the dreaded
UPDATE INTO statement, instead of five seconds in vi.)

Many of the problems listed for CSV, which come from its lack of
standardization, seem similar to those given for XML. "Commas
or tabs?" "How are new-lines represented?" If I was to use CSV,
I'd be able to just pick answers. However, fitting hierarchical
data into rows/columns just seems wrong, so I doubt that I'll
end up going that way.

As far as disambiguating authors, I believe that most journals
are now expecting an ORCID[2] (which doesn't help with papers
published before that came around).

As far as use of XML to store program state, I wouldn't ever
consider that. As noted above, I've used an RDBMS to do so.
It handles all of the concurrency issues for me. The current use
case is specifically for raw, static input.

Fascinating to find out that XML was originally designed to
mark up text, especially legal text.

It was nice to be reminded of what Matt Parker looked like when
he had hair.


[1] <https://en.wikipedia.org/wiki/Common_Information_Model_(electricity)>
[2] <https://orcid.org/>
--
Michael F. Stemper
Psalm 82:3-4
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-23 Thread Michael F. Stemper

On 23/09/2021 12.51, Eli the Bearded wrote:

Am 22.09.21 um 16:52 schrieb Michael F. Stemper:

On 21/09/2021 19.30, Eli the Bearded wrote:

Yes, CSV files can model that. But it would not be my first choice of
data format. (Neither would JSON.) I'd probably use XML.

Okay. 'Go not to the elves for counsel, for they will say both no
and yes.' (I'm not actually surprised to find differences of opinion.)


Well, I have a recommendation with my answer.


Sorry, didn't mean that to be disparaging.

--
Michael F. Stemper
This post contains greater than 95% post-consumer bytes by weight.
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-23 Thread Michael F. Stemper

On 22/09/2021 17.37, Dennis Lee Bieber wrote:

On Wed, 22 Sep 2021 09:52:59 -0500, "Michael F. Stemper"
 declaimed the following:

On 21/09/2021 19.30, Eli the Bearded wrote:

In comp.lang.python, Michael F. Stemper  wrote:



How does CSV handle hierarchical data? For instance, I have



Can CSV files model this sort of situation?





Yes, CSV files can model that. But it would not be my first choice of
data format. (Neither would JSON.) I'd probably use XML.


Okay. 'Go not to the elves for counsel, for they will say both no
and yes.' (I'm not actually surprised to find differences of opinion.)


You'd have to include a "level" (and/or data type if multiple objects
can be at the same level) field (as the first field) in CSV which
identifies how to parse the rest of the CSV data (well, technically, the
CSV module has "parsed" it -- in terms of splitting at commas, handling
quoted strings (which may contain commas which are not split points, etc.).

1-generator, name
2-fuel, name, UOM, heat-content, price
2-curve, name
3-point, X, Y
3-point, X, Y
...
2-curve, name
3-point, X, Y
3-point, X, Y


This reminds me of how my (former) employer imported data models into
our systems from the 1970s until the mid-2000s. We had 80-column records
(called "card images"), that would have looked like:

FUEL0 LIGNITETON13.610 043.581
UNIT1 COAL CREK1
UNIT2 ...

The specific columns for the start and end of each field on each record
were defined in a thousand-plus page document. (We modeled all of a
power system, not just economic data about generators.)

However, this doesn't seem like it would fit too well with the csv
module, since it requires a lot more logic on the part of the consuming
program.

Interesting flashback, though.

--
Michael F. Stemper
Deuteronomy 24:17
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-22 Thread Michael F. Stemper

On 21/09/2021 19.30, Eli the Bearded wrote:

In comp.lang.python, Michael F. Stemper  wrote:

I've heard of JSON, but never done anything with it.


You probably have used it inadvertantly on a regular basis over the
past few years. Websites live on it.


I used to use javascript when I was running Windows (up until 2009),
since it was the only programming language to which I had ready
access. Then I got a linux box and quickly discovered python. I
dropped javascript like a hot potato.


How does CSV handle hierarchical data? For instance, I have
generators[1], each of which has a name, a fuel and one or more
incremental heat rate curves. Each fuel has a name, UOM, heat content,
and price. Each incremental cost curve has a name, and a series of
ordered pairs (representing a piecewise linear curve).

Can CSV files model this sort of situation?


Can a string of ones and zeros encode the sounds of Bach, the images
of his sheet music, the details to reproduce his bust in melted plastic
extruded from nozzle under the control of machines?

Yes, CSV files can model that. But it would not be my first choice of
data format. (Neither would JSON.) I'd probably use XML.


Okay. 'Go not to the elves for counsel, for they will say both no
and yes.' (I'm not actually surprised to find differences of opinion.)


[1] The kind made of tons of iron and copper, filled with oil, and
rotating at 1800 rpm.


Those are rather hard to model in CSV, too, but I'm sure it could be
done.



for bonus round, use punched holes in paper to encode the ones and zeros


I've done cardboard.


--
Michael F. Stemper
No animals were harmed in the composition of this message.
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-22 Thread Michael F. Stemper

On 21/09/2021 16.21, Pete Forman wrote:

"Michael F. Stemper"  writes:

On 21/09/2021 13.49, alister wrote:

On Tue, 21 Sep 2021 13:12:10 -0500, Michael F. Stemper wrote:

It's my own research, so I can give myself the data in any format that I
like.


as far as I can see the main issue with XML is bloat, it tries to do
too many things & is a very verbose format, often the quantity of
mark-up can easily exceed the data contained within it. other formats
such a JSON & csv have far less overhead, although again not always
suitable.


I've heard of JSON, but never done anything with it.


Then you should certainly try to get a basic understanding of it. One
thing JSON shares with XML is that it is best left to machines to
produce and consume. Because both can be viewed in a text editor there
is a common misconception that they are easy to edit. Not so, commas are
a common bugbear in JSON and non-trivial edits in (XML unaware) text
editors are tricky.


Okay, after playing around with the example in Lubanovic's book[1]
I've managed to create a dict of dicts of dicts and write it to a
json file. It seems to me that this is how json handles hierarchical
data. Is that understanding correct?

Is this then the process that I would use to create a *.json file
to provide data to my various programs? Copy and paste the current
hard-coded assignment statements into REPL, use json.dump(dict,fp)
to write it to a file, and then read the file into each program
with json.load(fp)? (Actually, I'd write a function to do that,
just as I would with XML.)


Consider what overhead you should worry about. If you are concerned
about file sizes then XML, JSON and CSV should all compress to a similar
size.


Not a concern at all for my current application.


How does CSV handle hierarchical data? For instance, I have
generators[1], each of which has a name, a fuel and one or more
incremental heat rate curves. Each fuel has a name, UOM, heat content,
and price. Each incremental cost curve has a name, and a series of
ordered pairs (representing a piecewise linear curve).

Can CSV files model this sort of situation?


The short answer is no. CSV files represent spreadsheet row-column
values with nothing fancier such as formulas or other redirections.


Okay, that was what I suspected.


CSV is quite good as a lowest common denominator exchange format. I say
quite because I would characterize it by 8 attributes and you need to
pick a dialect such as MS Excel which sets out what those are. XML and
JSON are controlled much better. You can easily verify that you conform
to those and guarantee that *any* conformant parser can read your
content. XML is more powerful in that repect than JSON in that you can
define and enforce schemas. In your case the fuel name, UOM, etc. can be
validated with standard tools.


Yeah, validating against a DTD is pretty easy, since lxml.etree does all
of the work.


  In JSON all that checking is entirely
handled by the consuming program(s).

Well, the consumer's (almost) always going to need to do *some*
validation. For instance, as far as I can tell, a DTD can't specify
that there must be at least two of a particular item.

The designers of DTD seem to have taken the advice of MacLennan[2]:
  "The only reasonable numbers are zero, one, or infinity."

Which is great until you need to make sure that you have enough
points to define at least one line segment.


As in all such cases it is a matter of choosing the most apropriate tool
for the job in hand.


Naturally. That's what I'm exploring.


You might also like to consider HDF5. It is targeted at large volumes of
scientific data and its capabilities are well above what you need.


Yeah, I won't be looking at more than five or ten generators at most. A
small number is enough to confirm or refute the behavior that I'm
testing.


[1] _Introducing Python: Modern Computing in Simple Packages_,
Second Release, (c) 2015, Bill Lubanovic, O'Reilly Media, Inc.
[2] _Principles of Programming Languages: Design, Evaluation,
and Implementation_, Second Edition, (c) 1987, Bruce J. MacLennan,
Holt, Rinehart, & Winston
--
Michael F. Stemper
No animals were harmed in the composition of this message.
--
https://mail.python.org/mailman/listinfo/python-list


Re: XML Considered Harmful

2021-09-21 Thread Michael F. Stemper

On 21/09/2021 13.49, alister wrote:

On Tue, 21 Sep 2021 13:12:10 -0500, Michael F. Stemper wrote:


On the prolog thread, somebody posted a link to:
<https://dirtsimple.org/2004/12/python-is-not-java.html>

One thing that it tangentially says is "XML is not the answer."

I read this page right when I was about to write an XML parser to get
data into the code for a research project I'm working on.
It seems to me that XML is the right approach for this sort of thing,
especially since the data is hierarchical in nature.

Does the advice on that page mean that I should find some other way to
get data into my programs, or does it refer to some kind of misuse/abuse
of XML for something that it wasn't designed for?

If XML is not the way to package data, what is the recommended approach?


1'st can I say don't write your own XML parser, there are already a
number of existing parsers that should do everything you will need.  This
is a wheel that does not need re-inventing.


I was going to build it on top of xml.etree.ElementTree


2nd if you are not generating the data then you have to use whatever data
format you are supplied


It's my own research, so I can give myself the data in any format that I
like.


as far as I can see the main issue with XML is bloat, it tries to do too
many things & is a very verbose format, often the quantity of mark-up can
easily exceed the data contained within it.

other formats such a JSON & csv have far less overhead, although again
not always suitable.


I've heard of JSON, but never done anything with it.

How does CSV handle hierarchical data? For instance, I have
generators[1], each of which has a name, a fuel and one or more
incremental heat rate curves. Each fuel has a name, UOM, heat content,
and price. Each incremental cost curve has a name, and a series of
ordered pairs (representing a piecewise linear curve).

Can CSV files model this sort of situation?


As in all such cases it is a matter of choosing the most apropriate tool
for the job in hand.


Naturally. That's what I'm exploring.


[1] The kind made of tons of iron and copper, filled with oil, and
rotating at 1800 rpm.

--
Michael F. Stemper
This sentence no verb.
--
https://mail.python.org/mailman/listinfo/python-list


XML Considered Harmful

2021-09-21 Thread Michael F. Stemper

On the prolog thread, somebody posted a link to:
<https://dirtsimple.org/2004/12/python-is-not-java.html>

One thing that it tangentially says is "XML is not the answer."

I read this page right when I was about to write an XML parser
to get data into the code for a research project I'm working on.
It seems to me that XML is the right approach for this sort of
thing, especially since the data is hierarchical in nature.

Does the advice on that page mean that I should find some other
way to get data into my programs, or does it refer to some kind
of misuse/abuse of XML for something that it wasn't designed
for?

If XML is not the way to package data, what is the recommended
approach?
--
Michael F. Stemper
Life's too important to take seriously.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Question again

2021-09-18 Thread Michael F. Stemper

On 16/09/2021 19.11, Alan Gauld wrote:

On 16/09/2021 06:50, af kh wrote:

Hello,
I was doing some coding on a website called replit


I have no idea what that is but...


after answering 'no' or 'yes' after the last sentence I wrote,
the Python window shut off,


That's what you told it to do in the code.
Regardless of which answer the user gives the program
reaches the end and stops.


  in replit I added one more sentence, but it isn't shown on Python,


I dn;t know what this means.


#Gives greetings to the user
import random

...

#Ask to pick between numbers 1~10 to see if you will get lucky today: Third 
question
number = input("Please pick between numbers 1~10 to see your luck for today: ")

#From number 1~3 and an answer
if number == "1" or number == "2" or number == "3" :
   print("You're in grat luck today!")

#From number 4~7 and an answer
elif number == "4" or number == "5" or number == "6" :
   print("damn, bad luck is coming your way")


The cde and comment are not consistent.


#From number 8~10 and an answer
elif number == "7" or number == "8" or number == "9" or number == "10" :
   print("I cannot sense any luck today, try again next time")


Same here.


This is, of course, why comments shouldn't just translate the code
into English. They'll get out of synch. Instead, comments should say
*why* the code is doing what it does.

--
Michael F. Stemper
Exodus 22:21
--
https://mail.python.org/mailman/listinfo/python-list


Re: on writing a while loop for rolling two dice

2021-09-04 Thread Michael F. Stemper

On 04/09/2021 08.53, Hope Rouselle wrote:

Chris Angelico  writes:



And at this point, it's looking pretty much identical to the for loop
version. Ultimately, they're all the same and you can pick and choose
elements from each of them.


I see.  That's why C must have added the do-while, but yeah --- it's not
really worth it.


Kernighan and Ritchie agree(d) with you. Per _The C Programming
Language__:
  Experience shows that do-while is much less used that while
  and for.

(Second edition, Section 3.6, page 63)

--
Michael F. Stemper
Outside of a dog, a book is man's best friend.
Inside of a dog, it's too dark to read.
--
https://mail.python.org/mailman/listinfo/python-list


Re: The sqlite3 timestamp conversion between unixepoch and localtime

2021-09-03 Thread Michael F. Stemper

On 03/09/2021 01.14, Bob Martin wrote:

On 2 Sep 2021 at 20:25:27, Alan Gauld  wrote:

On 02/09/2021 20:11, MRAB wrote:


In one of them (I can't recall which is which) they change on the 4th
weekend of October/March in the other they change on the last weekend.



In the EU (and UK) it's the last Sunday in March/October.

In the US it's second Sunday in March and the first Sunday in November.

I know which one I find easier to remember!


Interesting. I remember it as closer than that. The bugs we found were
due to differences in the DST settings of the BIOS in the PCs. (They
were deliberately all sourced from DELL but the EU PCs had a slightly
different BIOS).

The differences you cite should have thrown up issues every year.
I must see if I can find my old log books...



ISTR that the USA changes were the same as the EU until a few years ago.

I remember thinking at the time it changed "why would they do that?"


It was part of the Energy Policy Act of 2005[1].

However, saying that doesn't explain "why".

The explanation given at the time was that it would save energy
because people wouldn't need to turn on their lights as early.
This ignored the fact that we needed to have them on later in
the morning.

The required studies were inconclusive, but some reported that
since it was light later in the day, people went driving around
in the evening, causing aggregate energy consumption to increase
rather than decrease.

One of the bill's sponsors said that having it be light later in
the day would "make people happy".

Talk at the time (which I never verified or refuted) said that he
got significant campaign contributions from a trade group for
outdoor cooking (grills, charcoal, usw) and that they wanted it
so that the grilling season would be longer, leading to more
revenue for them.

At the time, I was product manager for real-time control systems
for critical infrastructure. Having to collect the changes to
zoneinfo, whatever the equivalent file for Oracle was, revalidate
our entire system, and get information/patches to our North American
customers was annoying.


[1] <https://www.congress.gov/bill/109th-congress/house-bill/6>, Sec 110

--
Michael F. Stemper
If you take cranberries and stew them like applesauce they taste much
more like prunes than rhubarb does.
--
https://mail.python.org/mailman/listinfo/python-list


Re: urgent

2021-09-02 Thread Michael F. Stemper

On 31/08/2021 18.02, Barry wrote:


The big problem with >>> is that it means a third level quote in email clients.
So when people cut-n-paste REPL output it’s formatted badly by email clients.
A prompt that avoided that issue would be nice.


A little bit of piping fixes that:

username@hostname$ cat text
username@hostname$ python3
Python 3.5.2 (default, Jan 26 2021, 13:30:48)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys  # in the original, this line will be messed up
>>> sys.exit(0) # this one, too
username@hostname$ sed 's/^>>> /REPL> /' < text
username@hostname$ python3
Python 3.5.2 (default, Jan 26 2021, 13:30:48)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
REPL> import sys  # in the original, this line will be messed up
REPL> sys.exit(0) # this one, too
username@hostname$


--
Michael F. Stemper
What happens if you play John Cage's "4'33" at a slower tempo?
--
https://mail.python.org/mailman/listinfo/python-list


Re: The sqlite3 timestamp conversion between unixepoch and localtime can't be done according to the timezone setting on the machine automatically.

2021-08-31 Thread Michael F. Stemper

On 31/08/2021 16.13, Chris Angelico wrote:



But ultimately, it all just means that timezones are too hard for
humans to handle, and we MUST handle them using IANA's database. It is
the only way.


Tom Scott makes this point quite strongly on Computerphile:

<https://www.youtube.com/watch?v=-5wpm-gesOY>

And amusingly.

--
Michael F. Stemper
Always remember that you are unique. Just like everyone else.
--
https://mail.python.org/mailman/listinfo/python-list


Re: on slices, negative indices, which are the equivalent procedures?

2021-08-13 Thread Michael F. Stemper

On 11/08/2021 20.17, dn wrote:



I've been trying to remember if we had negative-steps in FORTRAN
do-loops


My text for Fortran 77 (the last version that I ever used) says
that negative increments are supported.

Ref: _FORTRAN 77: Language and Style_; Michael J. Merchant;
Wadsworth Publishing Company; (c) 1981; Page 125

It also says that zero increments are not supported. (Whew!)

--
Michael F. Stemper
87.3% of all statistics are made up by the person giving them.
--
https://mail.python.org/mailman/listinfo/python-list


Re: on slices, negative indices, which are the equivalent procedures?

2021-08-06 Thread Michael F. Stemper

On 05/08/2021 12.35, Jack Brandom wrote:

The FAQ at

   https://docs.python.org/3/faq/programming.html#what-s-a-negative-index

makes me think that I can always replace negative indices with positive
ones --- even in slices, although the FAQ seems not to say anything
about slices.

With slices, it doesn't seem to always work.  For instance, I can
reverse a "Jack" this way:


s = "Jack Brandom"
s[3 : -13 : -1]

'kcaJ'

I have no idea how to replace that -13 with a positive index.  Is it
possible at all?


I don't think so, because the second number (in this case -13) is the
index before which you stop. For example:

>>> s
'Jack Brandom'
>>> s[3:0:-1]
'kca'
>>> s[3:1:-1]
'kc'
>>>

However, since you want to go through item 0 in the original string,
you don't need a number there at all:

>>> s[3::-1]
'kcaJ'
>>>

Or, it you want to be more explicit, you could separately grab the
substring and then reverse it:

>>> s[:4][::-1]
'kcaJ'
>>>

Does any of this help?

--
Michael F. Stemper
If it isn't running programs and it isn't fusing atoms, it's just 
bending space.

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


Re: 'Pygame Module' not working

2021-07-31 Thread Michael F. Stemper

On 31/07/2021 03.37, 37_VA_VEER CHAKRABORTY wrote:

Hi,
I am a beginner in Python and I have started with the 'Pygame' module. I
was making a 'Flappy Bird' game with the module with the help of Youtube
videos. I was able to create a blank window. I had downloaded the game
assets in my computer in a folder called 'Python' and in a subfolder called
'assets'. I tried to upload the Flappy Bird picture and other sprites with
the code -
pygame.image.load('assets/Flappy Bird.png')
However, when I ran the script it was showing an error message - File not
found


Are you running your program in the parent directory of "assets"?

What happens when you go into the python interpreter (REPL) and import
pygame followed by executing that function?


--
Michael F. Stemper
Why doesn't anybody care about apathy?
--
https://mail.python.org/mailman/listinfo/python-list


Rotation of a cube

2021-07-29 Thread Michael F. Stemper

I would like to animate the rotation of a 3-cube. I know how to
do animation with pygame. My first thought was to set up a cube as
a list of coordinates, and then project those coordinates onto a
plane by ray-tracing from a viewpoint. I could then incrementally
rotate it using the rotation matrix[1], briefly showing each step.

However, it seems to me that this is a solved problem, so there is
probably a module that will do most of the scutwork for me. Any
suggestions on where to find such a module?

Thanks.


[1] <https://mathworld.wolfram.com/RotationMatrix.html>
--
Michael F. Stemper
This sentence no verb.
--
https://mail.python.org/mailman/listinfo/python-list


Syntactic sugar

2021-06-28 Thread Michael F. Stemper

I often want to execute a chunk of code n times

for iter in range(n):
  chunkofcode

Sometimes, the chunk of code doesn't care about which iteration
it's on. A week or two back, I would have sworn that I came across
a syntax for the above that eliminates the iteration counter.

This morning, I had use for that syntax, but couldn't find it
on-line or guess what it was. Does this syntax exist, or am I
simply imagining things?

Thanks,
--
Michael F. Stemper
There's no "me" in "team". There's no "us" in "team", either.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Syntactic sugar

2021-06-28 Thread Michael F. Stemper

On 28/06/2021 11.57, Stefan Ram wrote:

"Michael F. Stemper"  writes:

for iter in range(n):
   chunkofcode


   When the counter does not matter, people sometimes write "_":

for _ in range( n ):
 chunkofcode


That looks like what I wanted.

Thanks!

--
Michael F. Stemper
Indians scattered on dawn's highway bleeding;
Ghosts crowd the young child's fragile eggshell mind.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Optimizing Small Python Code

2021-06-23 Thread Michael F. Stemper

On 23/06/2021 08.17, Stefan Ram wrote:

"Avi Gross"  writes:

This can be made a one-liner too! LOL!


print( '1\n  0\n2\n  0\n  1\n3\n  0\n  1\n  2\n4\n  
0\n  1\n  2\n  3\n5\n  0\n  1\n  2\n  3\n  
4\n6\n  0\n  1\n  2\n  3\n  4\n  5\n' )


Unless I'm figuring ot wrong, you just took it from O(n^2) to
O(1). That deserves a Turing award or something.

--
Michael F. Stemper
You can lead a horse to water, but you can't make him talk like Mr. Ed
by rubbing peanut butter on his gums.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python

2021-06-14 Thread Michael F. Stemper

On 12/06/2021 01.25, Adarsh Kumar wrote:

How to  run python file in normal laptop
actually when i run python it is showing error pls tell me how to add python 
extension  in xammp


Are you trying to run a python program, as the first line suggests,
or are you trying to run python itself, as the second line says?

How are you trying to do this?

What error do you get? This is important. Do not paraphrase the error
message, copy and paste it directly. (Do not try to send a screenshot,
as it will be stripped off of your message.)

Also, in what environment are you doing this? Windows, MacOS, Linux,
something else? Specific version.


--
Michael F. Stemper
You can lead a horse to water, but you can't make him talk like Mr. Ed
by rubbing peanut butter on his gums.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python doesn't work

2021-05-30 Thread Michael F. Stemper

On 30/05/2021 06.23, Mr.Incognito wrote:

Hello

I downloaded the latest versioon of Python and tried to open several .py
files, but it doesn't open. 


It doesn't open, is that correct?


  It opens for a sec, then closes itself.


No, I guess that it does open.


My guess would be that the following happens:
1. You click on the file in some GUI.
2. The program contained in that file executes; taking a second or so.
3. Having done what you asked it to, it goes away.


--
Michael F. Stemper
87.3% of all statistics are made up by the person giving them.
--
https://mail.python.org/mailman/listinfo/python-list


Re: learning python ...

2021-05-27 Thread Michael F. Stemper

On 27/05/2021 16.13, Christian Gollwitzer wrote:

Am 25.05.21 um 06:08 schrieb hw:

On 5/25/21 12:37 AM, Greg Ewing wrote:

Python does have references to *objects*. All objects live on
the heap and are kept alive as long as there is at least one
reference to them.

If you rebind a name, and it held the last reference to an
object, there is no way to get that object back.


Are all names references?  When I pass a name as a parameter to a 
function, does the object the name is referring to, when altered by 
the function, still appear altered after the function has returned?  I 
wouldn't expect that ...


The strange thing, coming from a different language, is the apparent 
difference, if instead of a list, you pass an integer:


def f(a):
 a=5

l=3

f(l)
print(l)

> 3

Here, the "l" is not changed. The reason is that the statement "a=5" 
does NOT modify the object in a, but instead creates a new one and binds 
it to a. l still points to the old one. Whereas a.append() tells the 
object pointed to by a to change.


What was fun in Fortran was that you could do the following:

  CALL SS(3)
  PRINT *, 3
  END
  SUBROUTINE SS(K)
  K = 5
  RETURN
  END

The output of this gem would be 5, at least though Fortran 77. It was
call by reference, even for constants. (Every manual said not to do
this, of course.)

--
Michael F. Stemper
Outside of a dog, a book is man's best friend.
Inside of a dog, it's too dark to read.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Turtle module

2021-05-26 Thread Michael F. Stemper

On 26/05/2021 13.24, Stefan Ram wrote:

"Michael F. Stemper"  writes:

   What I would like to do is capture the
angle-representation mode on entry and restore it on return.



   another one:

def f( turtle_ ):
 my_turtle = turtle_.clone()
 # now work with my_turtle only


Oooh, I like this. It's proof against other types of bullets that
might come along.


   All of the above ideas have *not* been tested.


My first test found me with two arrows (turtle icons?) upon return.
I immediately realized what caused it, and put
   t.hideturtle()
at the end of my testbed function.

Thanks,
--
Michael F. Stemper
Economists have correctly predicted seven of the last three recessions.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Turtle module

2021-05-26 Thread Michael F. Stemper

On 26/05/2021 11.17, Chris Angelico wrote:

On Thu, May 27, 2021 at 1:59 AM Michael F. Stemper  wrote:




   What I would like to do is capture the
angle-representation mode on entry and restore it on return.
However, looking through the methods of turtle.Turtle(), I
can't find any means of capturing this information.

Similarly, I'd like to return with the pen in the same state
(up or down) as when my functions were called. Again, I can't
find any way to query the pen state.

How can my function get this information? Or do I need to be
sloppy and let the callers beware?


For the most part, this is what you want:

https://docs.python.org/3/library/turtle.html#turtle.pen


Just found the same thing myself and came back to report it. But,
immediately after your link is:
<https://docs.python.org/3/library/turtle.html#turtle.isdown>
which seems even better for up/down.


It doesn't seem to include the fullcircle state (which is what
.degrees() and .radians() set), and I'm not sure why. Worst case, it
is technically available as the ._fullcircle member, but I would
advise against using that if you can help it!


Well, I'll take your advice and not use it. Seems really sloppy to
change an attribute of an object as a side-effect, but I guess that
I'll have to be sloppy.

Thanks
--
Michael F. Stemper
Deuteronomy 10:18-19
--
https://mail.python.org/mailman/listinfo/python-list


Turtle module

2021-05-26 Thread Michael F. Stemper

I recently discovered the turtle module and have been playing
around with it for the last few days. I've started writing some
functions for turtles, and would like to make them a bit more
robustly than what I currently have.

In particular, I'd like the state of the turtle to be more or
less the same after the function return as it was before the
function invocation.

In order to turn the turtle, I need to select a way to represent
angles. I could use either degrees or radians (or, I suppose,
grads). However, for my functions to work, I need to set the
turtle to that mode. This means that I could possibly mess up
things for the caller. What I would like to do is capture the
angle-representation mode on entry and restore it on return.
However, looking through the methods of turtle.Turtle(), I
can't find any means of capturing this information.

Similarly, I'd like to return with the pen in the same state
(up or down) as when my functions were called. Again, I can't
find any way to query the pen state.

How can my function get this information? Or do I need to be
sloppy and let the callers beware?

--
Michael F. Stemper
2 Chronicles 19:7
--
https://mail.python.org/mailman/listinfo/python-list


Re: learning python ...

2021-05-25 Thread Michael F. Stemper

On 24/05/2021 18.30, Alan Gauld wrote:

On 24/05/2021 16:54, Michael F. Stemper wrote:


In my early days of writing python, I created lists named "list",
dictionaries named "dict", and strings named "str". I mostly know better
now, but sometimes still need to restrain my fingers.


I think most newbie programmers make that mistake. I certainly
did when learning Pascal back in the 80's.

But I was lucky, the tutorials were run by a guy who penalized
bad variable names severely and took a half-mark off for every
bad name. We very quickly learned to choose names that were
descriptive of the purpose rather than the type.


And when I write code that models something physical, I'll create
an object with attributes named after the real-world attributes
that such an object has. For instance, a generator (NOT in the
python sense) might have attributes such as:
RealPower
ReactivePower
IncrementalCostCurve (an object all on its own)
DispatchedPower

But, when I mess around with number theory, if I need a dict
that has naturals as keys and their aliquot sums as values, it's
easy enough to fall into that trap; especially if I already have
a function AliquotSum() that populates the dictionary as it grows.


--
Michael F. Stemper
Deuteronomy 10:18-19
--
https://mail.python.org/mailman/listinfo/python-list


Re: learning python ...

2021-05-25 Thread Michael F. Stemper

On 24/05/2021 23.08, hw wrote:

On 5/25/21 12:37 AM, Greg Ewing wrote:



Python does have references to *objects*. All objects live on
the heap and are kept alive as long as there is at least one
reference to them.

If you rebind a name, and it held the last reference to an
object, there is no way to get that object back.


Are all names references?  When I pass a name as a parameter to a 
function, does the object the name is referring to, when altered by the 
function, still appear altered after the function has returned?  I 
wouldn't expect that ...


I just ran a quick check and java (Ack, spit) does the same thing.


--
Michael F. Stemper
Isaiah 10:1-2
--
https://mail.python.org/mailman/listinfo/python-list


Re: learning python ...

2021-05-24 Thread Michael F. Stemper

On 24/05/2021 09.32, Rob Cliffe wrote:


One day you may want to write (as you can in Python)

     class int(int):
         .

to shadow the built-in 'int' type with a modified version.  I'm not 
suggesting this has many real world applications, but it can be fun to 
play with.  Python has a "consenting adults" policy: it assumes that if 
you do something weird, you're doing it deliberately, and it doesn't try 
to stop you.  I am sure after a little more experience with Python you 
will remember the commonest built-in types (int, float, list, dict, str 


In my early days of writing python, I created lists named "list",
dictionaries named "dict", and strings named "str". I mostly know better
now, but sometimes still need to restrain my fingers.

--
Michael F. Stemper
Nostalgia just ain't what it used to be.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Writers [Was: Re: Standarize TOML?]

2021-05-18 Thread Michael F. Stemper

On 18/05/2021 08.23, Jon Ribbens wrote:

On 2021-05-18, Michael F. Stemper  wrote:

On 17/05/2021 18.48, Terry Reedy wrote:



There are multiple packages.  There is no consensus on which to pick,
*if any*. Existing modules apparently include writers, which are
necessarily opinionated (as is formatting of C, Python, html, ...).  As
I just noted in the discussion, the stdlib does not have an html writer.


If I'm parsing this correctly, python supports something called a
"writer", which does not mean "somebody who writes python".


You are not parsing it correctly. Terry means that at least some
existing TOML modules for Python include facilities for outputting
("writing") TOML as well as reading it, and this makes choosing
between those modules more controversial as there are more subjective
opinions involved in the implementation of writing TOML as opposed to
only reading it.


Okay, thanks.

--
Michael F. Stemper
This post contains greater than 95% post-consumer bytes by weight.
--
https://mail.python.org/mailman/listinfo/python-list


Writers [Was: Re: Standarize TOML?]

2021-05-18 Thread Michael F. Stemper

On 17/05/2021 18.48, Terry Reedy wrote:

I disagree.  Rehashing *opinions* is pretty useless. The issues were 
already discussed on

https://discuss.python.org/t/adopting-recommending-a-toml-parser/4068

There are multiple packages.  There is no consensus on which to pick, 
*if any*. Existing modules apparently include writers, which are 
necessarily opinionated (as is formatting of C, Python, html, ...).  As 
I just noted in the discussion, the stdlib does not have an html writer. 


If I'm parsing this correctly, python supports something called a
"writer", which does not mean "somebody who writes python".

Since I've never heard of this[1], I searched on:
  python writer
but got stuff about how to write python and how to use python to write
to files.

Assuming that there is a python construct called a writer, could
somebody point me to somewhere that I could read up on them?


[1] Well, I've used csv.DictWriter() which might be an instance.
--
Michael F. Stemper
Galatians 3:28
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python script accessing own source code

2021-05-12 Thread Michael F. Stemper

On 12/05/2021 08.26, Dino wrote:

Hi, here's my (probably unusual) problem. Can a Python (3.7+) script 
access its own source code?


Here is a fairly simple python program that reads itself:


#!/usr/bin/python

import sys

with open( sys.argv[0], "rt" ) as myself:
  for line in myself:
junk = sys.stdout.write( "%s" % (line) )

sys.exit(0)


It's not bullet-proof. If you put it in a directory in your $PATH and
run it from somewhere else, it won't work.

--
Michael F. Stemper
I feel more like I do now than I did when I came in.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Bloody rubbish

2021-05-06 Thread Michael F. Stemper

On 06/05/2021 11.53, Wayne Lodahl wrote:

On 5/6/21 6:11 AM, Mr Flibble wrote:

Python is slow and significant whitespace is patently absurd.

Bloody rubbish, it's all bloody rubbish.

Message ends.

/Flibble


Machine language is so much simpler, and you can code with just a hexpad.


That's what the sixteen toggle switches are for.

--
Michael F. Stemper
Life's too important to take seriously.
--
https://mail.python.org/mailman/listinfo/python-list


Re: FileNotFoundError: [Errno 2] No such file or directory: ''

2021-04-14 Thread Michael F. Stemper

On 14/04/2021 12.55, Dan Stromberg wrote:

Open a cmd.exe, command.exe or powershell, and:

cd c:\my\dir\ect\ory
Then run your script.

Or put an os.chdir(r'c:\my\dir\ect\ory') at the top of your script.

Or use file = open(r'c:\my\dir\ect\ory\Egils Saga 1-15.txt', 'r')

BTW, "file" means something to python other than just a variable name.  You
can replace it, as your code below (and my example above) does, but it
obscures the thing you're replacing.  That's why I like to use file_
instead of file.


Personally, I'd use a meaningful name. For instance, I might do

saga = open(r'c:\my\dir\ect\ory\Egils Saga 1-15.txt', 'r')

or even

with open(r'c:\my\dir\ect\ory\Egils Saga 1-15.txt', 'r') as saga:

The latter form eliminates the need for saga.close(). (I'm sure that you
know that; it's directed at the OP.)

--
Michael F. Stemper
The FAQ for rec.arts.sf.written is at
<http://leepers.us/evelyn/faqs/sf-written.htm>
Please read it before posting.
--
https://mail.python.org/mailman/listinfo/python-list


Re: error of opening Python

2021-02-25 Thread Michael F. Stemper

On 25/02/2021 11.22, Botao Liu wrote:

Dear Python team,

This is my first time using Python, I tried to launch Python and it showed
"Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64
bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information." I
don't know what this meant and how to fix this. Could you please help me?


There isn't anything to fix. It's working just fine.


--
Michael F. Stemper
If you take cranberries and stew them like applesauce they taste much
more like prunes than rhubarb does.
--
https://mail.python.org/mailman/listinfo/python-list


Re: New Python implementation

2021-02-19 Thread Michael F. Stemper

On 19/02/2021 10.49, Avi Gross wrote:


But for an individual programmer, it is great to use whichever method feels
best for you, and especially if you came to python from another language
that method was borrowed from or vice versa. Being a rich language has pro's
and cons. LISP only had cons.


<https://www.youtube.com/watch?v=DcQDqZIN09I>

--
Michael F. Stemper
If you take cranberries and stew them like applesauce they taste much
more like prunes than rhubarb does.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python cannot count apparently

2021-02-08 Thread Michael F. Stemper

On 08/02/2021 13.12, Schachner, Joseph wrote:

This code works:
 mystr = "hello"
 for ch in mystr:
 print(ch, end="")

result is: hello

Note that the for loop does not use range.  Strings are iterable, that is they 
support Python's iteration protocol.  So, for ch in mystr: assigns one 
character from mystr to ch each time, each iteration gets the next character.
To prevent each character from appearing on a separate line (in Python 3) you need 
end="".   That is, don't put in the usual end-of-line ending.


Then you agree that the OP:


You must have done something to suppress the newlines after each call to 
print().

So it's quite obvious that the code you posted has very little to do with the 
code you ran. If you really want us to help, please directly copy and paste the 
exact code that you ran. We can't really help you with only guesses as to what 
you did.



--
Michael F. Stemper
Outside of a dog, a book is man's best friend.
Inside of a dog, it's too dark to read.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python cannot count apparently

2021-02-08 Thread Michael F. Stemper

On 07/02/2021 13.34, Philipp Daher wrote:

Hello,

I recently coded this snippet of code:
myString=„hello“
for i in range(len(myString):
  print(string[i])

And now for the weird part:

SOMETIMES, the output is this:

hello


Strange. When I fix the errors in what you posted:
- wrong character to start the string
- wrong variable name in the call to print()

I get[1]:


... myString="hello"
... for i in range(len(myString)):
...   print( myString[i] )
...
h
e
l
l
o
...

You must have done something to suppress the newlines after
each call to print().

So it's quite obvious that the code you posted has very little
to do with the code you ran. If you really want us to help, please
directly copy and paste the exact code that you ran. We can't
really help you with only guesses as to what you did.



[1] (leading > replaced with . to fool news clients)
--
Michael F. Stemper
Galatians 3:28
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-16 Thread Michael F. Stemper

On 15/01/2021 17.17, dn wrote:

On 16/01/2021 11.40, Michael F. Stemper wrote:

On 15/01/2021 16.01, Chris Angelico wrote:

On Sat, Jan 16, 2021 at 8:56 AM Michael F. Stemper
 wrote:

On 15/01/2021 15.26, Stefan Ram wrote:

"Michael F. Stemper"  writes:

On 15/01/2021 14.01, Stefan Ram wrote:



__import__( "math" ).sqrt( 4 )

I had no idea that syntax existed, and find it completely at odds
with The Zen of Python. I'm torn between forgetting that I ever saw
it and using it for some evilly-obfuscated code.


     When one collects snippets of Python code that are intended
     to be inserted into programs, a snippet usually would have
     to consist of two parts: One part to be inserted at the top
     of the program, into the imports section, and then the actual
     snippet.
     "__import__" allows to write snippets that can be inserted
     as they are without the need to do insertions at two different
     places. (Possibly with a tool to later normalize the insertions
     to the usual style.)


I'm not sure how that works. In Python, you can just put the imports
where you want them - why would the __import__ function be needed?


import is 'syntactic sugar' for __import__().


And any high-level language is, from a certain point of view, syntactic
sugar for entering the machine-language instructions using the toggle
switches on the front panel. The way that Turing meant for us to do it.


More seriously, it's like creating a class object by

 MyClass = type('MyClass', (), {})

whereas it's far easier (for most of us) to use

 class MyClass( etc )


As well as far easier to comprehend and maintain.


I have no idea what PEP-8 has to say on the subject. However, my coding
style *generally* puts all of the imports up front, right after the
prologue (program description, revision history, uzw).


This is indeed received-wisdom.

However it does not disallow (yuk: double-negative!) coding an import
statement elsewhere, eg a routine which is only executed during some
invocations, but not others.


Hence the emphasized "generally". For instance, one of my programs has
an option to plot its results. If that option is selected, matplotlib is
imported -- way at the end, after all of the number-crunching.

I think that we're in agreement here.


What you may like to consider about "prolog[ue]s" is whether they belong
'in' the code (plenty of arguments 'for') or within the VCS (plenty of
arguments here too)...

eg1: how easy is it to establish when a particular decision/code-change
was made (more than one week ago)? - particularly if changes were
subsequent made 'on top of' that change?

eg2: is it a good idea to use 'Python constants' to display the
program(me) name and (perhaps) a version number on the
terminal/application window?


Such as "%prog"? Or "sys.argv[0]"? Quite useful for help text and
diagnostic messages, with no need to hard-code the program name
into the program. Which would cause confusion if a user wanted to
rename/alias the program.

--
Michael F. Stemper
What happens if you play John Cage's "4'33" at a slower tempo?
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 15/01/2021 16.01, Chris Angelico wrote:

On Sat, Jan 16, 2021 at 8:56 AM Michael F. Stemper  wrote:


On 15/01/2021 15.26, Stefan Ram wrote:

"Michael F. Stemper"  writes:

On 15/01/2021 14.01, Stefan Ram wrote:



__import__( "math" ).sqrt( 4 )

I had no idea that syntax existed, and find it completely at odds
with The Zen of Python. I'm torn between forgetting that I ever saw
it and using it for some evilly-obfuscated code.


When one collects snippets of Python code that are intended
to be inserted into programs, a snippet usually would have
to consist of two parts: One part to be inserted at the top
of the program, into the imports section, and then the actual
snippet.
"__import__" allows to write snippets that can be inserted
as they are without the need to do insertions at two different
places. (Possibly with a tool to later normalize the insertions
to the usual style.)


I'm not sure how that works. In Python, you can just put the imports
where you want them - why would the __import__ function be needed?


I have no idea what PEP-8 has to say on the subject. However, my coding
style *generally* puts all of the imports up front, right after the
prologue (program description, revision history, uzw).


I am confuzzed.


It's a common condition.


--
Michael F. Stemper
Life's too important to take seriously.
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 15/01/2021 15.26, Stefan Ram wrote:

"Michael F. Stemper"  writes:

On 15/01/2021 14.01, Stefan Ram wrote:

__import__( "math" ).sqrt( 4 )

I had no idea that syntax existed, and find it completely at odds
with The Zen of Python. I'm torn between forgetting that I ever saw
it and using it for some evilly-obfuscated code.


   When one collects snippets of Python code that are intended
   to be inserted into programs, a snippet usually would have
   to consist of two parts: One part to be inserted at the top
   of the program, into the imports section, and then the actual
   snippet.


This statement led inevitably to:

>>> sqrt = __import__("math").sqrt
>>> sqrt(4)
2.0
>>>

I don't know why; it just did.


   "__import__" allows to write snippets that can be inserted
   as they are without the need to do insertions at two different
   places. (Possibly with a tool to later normalize the insertions
   to the usual style.)


That's much too mature. Es ist Feierabend!

--
Michael F. Stemper
2 Chronicles 19:7
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 15/01/2021 14.01, Stefan Ram wrote:

"Michael F. Stemper"  writes:



  Of these, only EcmaScript has
Math.sqrt() as part of the language, and that could be partly
due to the fact that the language doesn't have any concept of
"import" or "include".


   You do not need to use the import statement in Python,
   but can also use the expression

__import__( "math" ).sqrt( 4 )


I had no idea that syntax existed, and find it completely at odds
with The Zen of Python. I'm torn between forgetting that I ever saw
it and using it for some evilly-obfuscated code.

I hope that it satisfies the OP.

--
Michael F. Stemper
I feel more like I do now than I did when I came in.
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 15/01/2021 14.02, Chris Angelico wrote:

On Sat, Jan 16, 2021 at 6:21 AM Michael F. Stemper  wrote:

Here's the status of the square root function in various languages,
in the order that I encountered them:

FORTRANPart of the language
Pascal Part of the language
SNOBOL Part of the language
c  Need to #include 
clisp  Part of the language
EcmaScript Part of the language
python Need to import from math
Java   Need to import from java.math

The four that appear to be in the most use currently are c,
EcmaScript, python, and Java. Of these, only EcmaScript has
Math.sqrt() as part of the language, and that could be partly
due to the fact that the language doesn't have any concept of
"import" or "include".



Cool. Now tell me: Of all the languages that have a built-in global
name SQRT (which does not include ECMAScript,


I wasn't looking at how the various languages spell it, I was just looking
at the fact that it could be used directly. Since ECMAScript has a
function Math.sqrt(), I counted it as being a direct part of the
language.


 and for the record, ES
does have imports),


I stand corrected. So I could say something like "import Math.*" and
then use "sqrt()" directly?


  how many of them have a built-in or syntax for
dictionaries/mappings?


Beats me. That wasn't what the OP was complaining about. I just did this
little ad-hoc survey to show that more modern languages don't have an
"inherent" square root function, so python's hardly unique.


  I would put it to you that the ability to look
up something by name in a tree, hashtable, or equivalent, is *at
least* as useful as the ability to calculate a square root.


I don't think that I've used the square root function since I took a
course in geometry in the fall of 2019, so I have no grounds to dispute.


Languages differ. I don't see why it's so important to focus on just
one thing - and to complain that, even though it's in the standard
library, you have to use an import command to get it.


You should probably direct this to the person who complained rather than
the person who showed that the complaint wasn't really consistent with
modern language direction, while python's handling of the square root
function is consistent.


--
Michael F. Stemper
Galatians 3:28
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 15/01/2021 14.00, Chris Green wrote:

Michael F. Stemper  wrote:

On 14/01/2021 13.00, Rob Cliffe wrote:

On 14/01/2021 17:44, Denys Contant wrote:



I don't understand why sqrt is not a built-in function.
Why do we have to first import the function from the math module?
I use it ALL THE TIME!

I agree that, especially if you have experience in other languages, this
feels odd, and I have some sympathy for you.


I cut my teeth on FORTRAN, which has SQRT() as part of the
language. At least 3, 4, and 5 did; I never used later versions.


Surely III, IV and V.  I was definitely Fortran IV


I think that the listings for my cross-compiles for the Cyber 1700
actually said "FORTRAN 3" at the top of each page, but that was over
three decades back, so it's a little hazy. There weren't any standards
for it anyway.

You're spot-on for FORTRAN IV.

A quick check of wikipedia shows that the last one was better referred
to as FORTRAN 77, but I think that the NOS command to invoke the
compiler was FTN5.

--
Michael F. Stemper
Galatians 3:28
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 14/01/2021 13.00, Rob Cliffe wrote:

On 14/01/2021 17:44, Denys Contant wrote:



I don't understand why sqrt is not a built-in function.
Why do we have to first import the function from the math module?
I use it ALL THE TIME!
I agree that, especially if you have experience in other languages, this 
feels odd, and I have some sympathy for you.


I cut my teeth on FORTRAN, which has SQRT() as part of the
language. At least 3, 4, and 5 did; I never used later versions.

Here's the status of the square root function in various languages,
in the order that I encountered them:

FORTRANPart of the language
Pascal Part of the language
SNOBOL Part of the language
c  Need to #include 
clisp  Part of the language
EcmaScript Part of the language
python Need to import from math
Java   Need to import from java.math

The four that appear to be in the most use currently are c,
EcmaScript, python, and Java. Of these, only EcmaScript has
Math.sqrt() as part of the language, and that could be partly
due to the fact that the language doesn't have any concept of
"import" or "include".



--
Michael F. Stemper
This email is to be read by its intended recipient only. Any other party
reading is required by the EULA to send me $500.00.
--
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Michael F. Stemper

On 12/01/2021 10.40, Michael F. Stemper wrote:


Modeling of electric power systems:
- load behavior in response to conservation load reduction


Sorry, that should have been "conservation voltage reduction".


--
Michael F. Stemper
Psalm 82:1-4
--
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Michael F. Stemper

On 11/01/2021 14.37, DonK wrote:


I've installed Python 3.7, the PyCharm IDE and watched some Youtube
tutorials


I would suggest that instead of watching tutorials, you open up your IDE
and start writing stuff. Get an introductory python book (I used the
O'Reilly _Introducing Python_), start at the beginning, and type in each
example. Then, tweak it to see what happens.


I've seen some Python gui frameworks like Tkinter, PyQt, etc. but they
look kinda like adding a family room onto a 1986 double wide mobile
home, and they look even more complicated than creating a GUI from
scratch in C++ with a message loop, raising events . . .


I haven't really got my head around GUI programming myself. I tried to
write one with tkinter based on on-line examples, but didn't have any
conceptual framekwork, so it didn't work too well. I saw in a post here
that there are actually books on it, so I might pick one up and try
again.


So, what do you folks use Python for?


Since you asked:

Various command-line utilities, including:
- comparing the contents of two directories
- ad-hoc linear regression
- validation of DTDs
- sanity check of nesting symbols in TeX files
- ad-hoc plotting

Maintaining and querying of data bases:
- five-minute values of local temperatures
- Action items for an organization of which I'm secretary
- my own to-do list
- non-isomorphic groups that have isomorphic character tables

Modeling of electric power systems:
- load behavior in response to conservation load reduction
- generator and governor response to system load
- economic dispatch of generators, including those with non-monotonic 
incremental cost curves

(last two are very much works in progress)

Mathematics:
- experiments with number theory and combinatorics
- composition of permutations of a set
- properties of minimal paths through a C_m x C_n lattice
- generating tikz commands for geometric diagrams in TeX documents
- unstructured and uneducated exploration of Conway's Game of Life

--
Michael F. Stemper
2 Chronicles 19:7
--
https://mail.python.org/mailman/listinfo/python-list


Re: primitive password cracker

2021-01-09 Thread Michael F. Stemper

Is this "code golf"? Can anybody play? Here's another approach:

Define a function like this:

def embiggen(wordlist):
  alpha = 'abc'
  return [x for x in alpha] + [x+y for x in alpha for y in wordlist]

It makes every word in its input one letter longer in each possible
way, and returns all of the words thus created as well as all of the
one-letter words. (I'm using a very short alphabet, due to the
exponential growth.)

In REPL:
>>> words = []
>>> words = embiggen(words)
>>> words
['a', 'b', 'c']
>>> words = embiggen(words)
>>> words
['a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
>>> words = embiggen(words)
>>> words
['a', 'b', 'c', 'aa', 'ab', 'ac', 'aaa', 'aab', 'aac', 'aba', 'abb', 
'abc', 'aca', 'acb', 'acc', 'ba', 'bb', 'bc', 'baa', 'bab', 'bac', 
'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'ca', 'cb', 'cc', 'caa', 
'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']

>>> words = embiggen(words)
>>> len(words)
120
>>>

It's obvious that this could be called from a for-loop with no
modification, which I believe is what the OP wanted.

--
Michael F. Stemper
Deuteronomy 24:17
--
https://mail.python.org/mailman/listinfo/python-list


Re: dayofyear is not great when going into a new year

2021-01-09 Thread Michael F. Stemper

On 09/01/2021 01.51, Christian Gollwitzer wrote:

Am 05.01.21 um 23:56 schrieb Eli the Bearded:

Elijah
--
also finds "week starts on Monday" to be oddball about ISO-8601



In Europe, the week starts on Monday - hence, Saturday and Sunday are 
the last days of the week or the "weekend". Starting on Sunday is weird 
for us, because then the weekend is split into the first and last day of 
the week (?)


A week is like a piece of string. It has two ends.


--
Michael F. Stemper
Deuteronomy 24:17
--
https://mail.python.org/mailman/listinfo/python-list


Re: dayofyear is not great when going into a new year

2021-01-05 Thread Michael F. Stemper

On 05/01/2021 15.27, Chris Angelico wrote:

On Wed, Jan 6, 2021 at 8:02 AM Martin Schöön  wrote:



I have had some Python fun with COVID-19 data. I have done
some curve fitting and to make that easier I have transformed
date to day of year. Come end of 2020 and beginning of 2021
and this idea falls on its face.



There are multiple definitions for "day of year", depending on how you
want to handle certain oddities. The simplest is to identify Jan 1st
as 1, Jan 2nd as 2, etc, to Dec 31st as either 365 or 366; but some
libraries will define the year as starting with the week that contains
the Thursday, or something, and then will define days of year
accordingly.

If you want an easy way to graph day-by-day data and the exact day
numbers are irrelevant, what I'd recommend is: Convert the date into
Unix time, divide by 86400, floor it. That'll give you a Julian-style
date number where Jan 1st 1970 is 0, Jan 2nd is 1, etc, and at the end
of a year, it'll just keep on incrementing. That would get you past
the 2020/2021 boundary pretty smoothly.


Possibly better than rolling your own is using standard stuff:

>>> from datetime import date,datetime
>>> datetime.toordinal(date(2020,1,1))
737425
>>> datetime.toordinal(date(2021,1,5))
737795
>>> datetime.toordinal(date(2021,1,5)) - datetime.toordinal(date(2020,1,1))
370
>>>

--
Michael F. Stemper
This post contains greater than 95% post-consumer bytes by weight.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Function returns old value

2020-12-19 Thread Michael F. Stemper

On 18/12/2020 00.09, Cameron Simpson wrote:

On 17Dec2020 14:22, Michael F. Stemper  wrote:

On 17/12/2020 03.57, Peter J. Holzer wrote:

On 2020-12-17 03:06:32 -, Bischoop wrote:



With newer vims that's rarely necessary though since they can
distinguish
between input that was pasted and input that was typed.


Mine doesn't seem to (vim inside a MacOS iTerm).


I thought that I was going nuts when I encountered that. Any idea how to
defeat such a so-called 'feature"?


You mean having vim figure that out? I dunno. I came here from vi and
haven't fully embraced al the stuff vim has.


What I want is for vi to treat all input the same, whether it comes
directly from the keyboard, or from a copy/paste buffer.

It did everything fine from '92 when I started using it on AIX until a
year or two back when I briefly went to Ubuntu 18.04 LTS. Then, I could
paste a command into it, and it would insert it into the text, rather
than executing it. Or, I'd paste (in input mode; repeatedly verified)
some TeX and it would decide that it was really a command and execute
it.

And I've just realized which group this is, so my complaint is
completely off-topic. Sorry.

--
Michael F. Stemper
Deuteronomy 24:17
--
https://mail.python.org/mailman/listinfo/python-list


Re: Function returns old value

2020-12-17 Thread Michael F. Stemper

On 17/12/2020 03.57, Peter J. Holzer wrote:

On 2020-12-17 03:06:32 -, Bischoop wrote:

pasting from my IDE to vim/slrn was messing syntax,


You can

:set paste

in vim to prevent it from messing with pasted content (don't forget to
set nopaste afterwards).


What's the difference between that and
:set ai
and
:set noai


With newer vims that's rarely necessary though since they can distinguish
between input that was pasted and input that was typed.


I thought that I was going nuts when I encountered that. Any idea how to
defeat such a so-called 'feature"?


--
Michael F. Stemper
The name of the story is "A Sound of Thunder".
It was written by Ray Bradbury. You're welcome.
--
https://mail.python.org/mailman/listinfo/python-list


  1   2   >