Re: Best-practice for formatted string literals and localization?

2020-12-07 Thread Hartmut Goebel

Am 30.11.20 um 19:58 schrieb Chris Angelico:

Not really, no.


Thanks for confirming my apprehension.

--
Regards
Hartmut Goebel

| Hartmut Goebel  | h.goe...@crazy-compilers.com   |
| www.crazy-compilers.com | compilers which you thought are impossible |

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


Re: Best-practice for formatted string literals and localization?

2020-12-07 Thread Hartmut Goebel

Am 01.12.20 um 19:40 schrieb Dieter Maurer:

Usually, the translation machinery has special ways to
provide parameters for translations.
For example with `zope.i18nmessageid`, you can use
`_(msg, mapping=)` to provide parameters
to the translations -- as in your case `count`).
Check, what parameter support your translation machinery support.


Thanks for this hint. I'm using the stdlib, which AFAIU does not support 
that. (Anyhow it would be easy to implement such a wrapper)


--
Regards
Hartmut Goebel

| Hartmut Goebel  | h.goe...@crazy-compilers.com   |
| www.crazy-compilers.com | compilers which you thought are impossible |

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


Re: how to plot the FFT of a list of values

2020-12-07 Thread Thomas Jollans

On 05/12/2020 23:08, Christian Gollwitzer wrote:

Am 05.12.20 um 18:16 schrieb Boris Dorestand:

I have 16 values of the period sequence 1, 2, 4, 8, 1, 2, 4, 8, ...  I
compute its fourier transform using


from scipy import fft, ifft
x = [1,2,4,8,1,2,4,8]
fft(x)

array([ 30. +0.j,   0. +0.j,  -6.+12.j,   0. +0.j, -10. +0.j, 0. +0.j,
 -6.-12.j,   0. +0.j])

Now how can I plot these values?  I would like to plot 16 values.  What
do I need to do here?  Can you show an example?



Usually, for the FFT of real input data, you plot only the magnitude 
or square of the complex array, and usually on a logscale. So:


import pylab


Don't use pylab.

https://matplotlib.org/api/index.html#module-pylab

Use matplotlib.pyplot directly instead. "plt" is a popular shorthand:

from matplotlib import pyplot as plt

#...

plt.semilogy(...) # or plt.plot, etc.


- Thomas



import numpy as np

fx = fft(x)

pylab.semilogy(np.abs(fx))
pylab.show()



Christian





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


Letter replacer - suggestions?

2020-12-07 Thread Bischoop


I worked on my wee script that replaces a letters: https://bpa.st/OYBQ .
I would like to have some suggestions about the code from more
experienced programmers, the code does work and do its job but perhaps
could work in a better way.

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


Re: Letter replacer - suggestions?

2020-12-07 Thread MRAB

On 2020-12-07 15:48, Bischoop wrote:


I worked on my wee script that replaces a letters: https://bpa.st/OYBQ .
I would like to have some suggestions about the code from more
experienced programmers, the code does work and do its job but perhaps
could work in a better way.

Thanks



> word = input( f'input word you want to change letters in: ')

There's no need for the f prefix.

> print(f' Your word to change: ,{word}')

Is the comma a typo?

> word_list = list(word)
> change_this = input(f'Enter the letters you want to change: ')

There's no need for the f prefix.

> replace_with = input(f'Enter the letters to replace with: ')

There's no need for the f prefix.

> change_this_list = list(change_this)
> replace_with_list = list(replace_with)
>
> while True:
> try:
> for element in word_list:
> for x in change_this_list:
> if element == x:
> to = word_list.index(element)
> replace = change_this_list.index(x)
> word_list[to] = replace_with_list[replace]
> new_word = ''.join(word_list)
> print(f'{new_word}')

The f-string is overkill. You might as well just have:

 print(new_word)

> break
> except:

Avoid a 'bare' except unless you _really_ mean it, which is virtually 
never. Catch only those exceptions that you're going to handle.


> print(f'nope')


You can make it a lot shorter and faster by using a dict. The entire 
while loop section can be replaced with:


replacements = dict(zip(change_this, replace_with))
new_word = ''.join(replacements.get(letter, letter) for letter in word)
print(new_word)
--
https://mail.python.org/mailman/listinfo/python-list


Re: Error

2020-12-07 Thread Michael Torrie
On 12/7/20 11:07 AM, Barry Fitzgerald wrote:
> I did the pip install I did the pip install pygameThe pip install
> pgzero I get this error C:\Users\barol>pip install pgzeroDefaulting
> to user installation because normal site-packages is not
> writeableCollecting pgzero  Using cached pgzero-1.2-py3-none-any.whl
> (69 kB)Collecting numpy  Using cached
> numpy-1.19.4-cp39-cp39-win_amd64.whl (13.0 MB)Collecting
> pygame<2.0,>=1.9.2  Using cached pygame-1.9.6.tar.gz (3.2 MB)
> ERROR: Command errored out with exit status 1: command:
> 'c:\program files\python39\python.exe' -c 'import sys, setuptools,
> tokenize; sys.argv[0] =
> '"'"'C:\\Users\\barol\\AppData\\Local\\Temp\\pip-install-loo9yev7\\pygame_5aee70f17f294e14b6187b13f07afa31\\setup.py'"'"';
> __file__='"'"'C:\\Users\\barol\\AppData\\Local\\Temp\\pip-install-loo9yev7\\pygame_5aee70f17f294e14b6187b13f07afa31\\setup.py'"'"';f=getattr(tokenize,
> '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"',
> '"'"'\n'"'"');f.close();exec(compile(code, __file__,
> '"'"'exec'"'"'))' egg_info --egg-base
> 'C:\Users\barol\AppData\Local\Temp\pip-pip-egg-info-rdmw_7gl'
> cwd:
> C:\Users\barol\AppData\Local\Temp\pip-install-loo9yev7\pygame_5aee70f17f294e14b6187b13f07afa31\
> Complete output (17 lines):
> 
> WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
> Using WINDOWS configuration...
The problem is there is no pre-compiled PyGame Zero package yet for
Python 3.9.  So your system is trying to compile it from source.
Probably your best bet is to remove Python 3.9 and install Python 3.8.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Error

2020-12-07 Thread Mats Wichmann

On 12/7/20 11:13 AM, Michael Torrie wrote:

On 12/7/20 11:07 AM, Barry Fitzgerald wrote:

I did the pip install I did the pip install pygameThe pip install
pgzero I get this error C:\Users\barol>pip install pgzeroDefaulting
to user installation because normal site-packages is not
writeableCollecting pgzero  Using cached pgzero-1.2-py3-none-any.whl
(69 kB)Collecting numpy  Using cached
numpy-1.19.4-cp39-cp39-win_amd64.whl (13.0 MB)Collecting
pygame<2.0,>=1.9.2  Using cached pygame-1.9.6.tar.gz (3.2 MB)
ERROR: Command errored out with exit status 1: command:
'c:\program files\python39\python.exe' -c 'import sys, setuptools,
tokenize; sys.argv[0] =
'"'"'C:\\Users\\barol\\AppData\\Local\\Temp\\pip-install-loo9yev7\\pygame_5aee70f17f294e14b6187b13f07afa31\\setup.py'"'"';
__file__='"'"'C:\\Users\\barol\\AppData\\Local\\Temp\\pip-install-loo9yev7\\pygame_5aee70f17f294e14b6187b13f07afa31\\setup.py'"'"';f=getattr(tokenize,
'"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"',
'"'"'\n'"'"');f.close();exec(compile(code, __file__,
'"'"'exec'"'"'))' egg_info --egg-base
'C:\Users\barol\AppData\Local\Temp\pip-pip-egg-info-rdmw_7gl'
cwd:
C:\Users\barol\AppData\Local\Temp\pip-install-loo9yev7\pygame_5aee70f17f294e14b6187b13f07afa31\
Complete output (17 lines):

WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
Using WINDOWS configuration...

The problem is there is no pre-compiled PyGame Zero package yet for
Python 3.9.  So your system is trying to compile it from source.


... which nearly always fails on Windows, unless you're previously 
ensured your setup exactly matches what that project wants.



Probably your best bet is to remove Python 3.9 and install Python 3.8.


You can check the status on pypi by searching for a package and then 
clicking on "Download files".  Doing that in this case shows that pygame 
2.0 is indeed available for Python 3.9:


https://pypi.org/project/pygame/#files

BUT, above it's trying to compile pygame 1.9.2, because *it* presumably 
doesn't have a Py3.9 version.  So the guess is that pgzero is pinned to 
a particular pygame version, and that version isn't available for 3.9, 
so this story may be a little more complex than most of them are. 
Unpacking it shows the requirement indeed excludes pygame 2.0:


pygame<2.0,>=1.9.2








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


Re: Error

2020-12-07 Thread MRAB

On 2020-12-07 18:13, Michael Torrie wrote:

On 12/7/20 11:07 AM, Barry Fitzgerald wrote:

I did the pip install I did the pip install pygameThe pip install
pgzero I get this error C:\Users\barol>pip install pgzeroDefaulting
to user installation because normal site-packages is not
writeableCollecting pgzero  Using cached pgzero-1.2-py3-none-any.whl
(69 kB)Collecting numpy  Using cached
numpy-1.19.4-cp39-cp39-win_amd64.whl (13.0 MB)Collecting
pygame<2.0,>=1.9.2  Using cached pygame-1.9.6.tar.gz (3.2 MB)
ERROR: Command errored out with exit status 1: command:
'c:\program files\python39\python.exe' -c 'import sys, setuptools,
tokenize; sys.argv[0] =
'"'"'C:\\Users\\barol\\AppData\\Local\\Temp\\pip-install-loo9yev7\\pygame_5aee70f17f294e14b6187b13f07afa31\\setup.py'"'"';
__file__='"'"'C:\\Users\\barol\\AppData\\Local\\Temp\\pip-install-loo9yev7\\pygame_5aee70f17f294e14b6187b13f07afa31\\setup.py'"'"';f=getattr(tokenize,
'"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"',
'"'"'\n'"'"');f.close();exec(compile(code, __file__,
'"'"'exec'"'"'))' egg_info --egg-base
'C:\Users\barol\AppData\Local\Temp\pip-pip-egg-info-rdmw_7gl'
cwd:
C:\Users\barol\AppData\Local\Temp\pip-install-loo9yev7\pygame_5aee70f17f294e14b6187b13f07afa31\
Complete output (17 lines):

WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
Using WINDOWS configuration...

The problem is there is no pre-compiled PyGame Zero package yet for
Python 3.9.  So your system is trying to compile it from source.
Probably your best bet is to remove Python 3.9 and install Python 3.8.

There's no need to remove Python 3.9 first; Python 3.8 can be installed 
alongside it.

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


Re: Error

2020-12-07 Thread MRAB

On 2020-12-07 18:29, Mats Wichmann wrote:

On 12/7/20 11:13 AM, Michael Torrie wrote:

On 12/7/20 11:07 AM, Barry Fitzgerald wrote:

I did the pip install I did the pip install pygameThe pip install
pgzero I get this error C:\Users\barol>pip install pgzeroDefaulting
to user installation because normal site-packages is not
writeableCollecting pgzero  Using cached pgzero-1.2-py3-none-any.whl
(69 kB)Collecting numpy  Using cached
numpy-1.19.4-cp39-cp39-win_amd64.whl (13.0 MB)Collecting
pygame<2.0,>=1.9.2  Using cached pygame-1.9.6.tar.gz (3.2 MB)
ERROR: Command errored out with exit status 1: command:
'c:\program files\python39\python.exe' -c 'import sys, setuptools,
tokenize; sys.argv[0] =
'"'"'C:\\Users\\barol\\AppData\\Local\\Temp\\pip-install-loo9yev7\\pygame_5aee70f17f294e14b6187b13f07afa31\\setup.py'"'"';
__file__='"'"'C:\\Users\\barol\\AppData\\Local\\Temp\\pip-install-loo9yev7\\pygame_5aee70f17f294e14b6187b13f07afa31\\setup.py'"'"';f=getattr(tokenize,
'"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"',
'"'"'\n'"'"');f.close();exec(compile(code, __file__,
'"'"'exec'"'"'))' egg_info --egg-base
'C:\Users\barol\AppData\Local\Temp\pip-pip-egg-info-rdmw_7gl'
cwd:
C:\Users\barol\AppData\Local\Temp\pip-install-loo9yev7\pygame_5aee70f17f294e14b6187b13f07afa31\
Complete output (17 lines):

WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
Using WINDOWS configuration...

The problem is there is no pre-compiled PyGame Zero package yet for
Python 3.9.  So your system is trying to compile it from source.


... which nearly always fails on Windows, unless you're previously
ensured your setup exactly matches what that project wants.


Probably your best bet is to remove Python 3.9 and install Python 3.8.


You can check the status on pypi by searching for a package and then
clicking on "Download files".  Doing that in this case shows that pygame
2.0 is indeed available for Python 3.9:

https://pypi.org/project/pygame/#files

BUT, above it's trying to compile pygame 1.9.2, because *it* presumably
doesn't have a Py3.9 version.  So the guess is that pgzero is pinned to
a particular pygame version, and that version isn't available for 3.9,
so this story may be a little more complex than most of them are.
Unpacking it shows the requirement indeed excludes pygame 2.0:

pygame<2.0,>=1.9.2


Christoph Gohlke's site has wheels for pygame on Python 3.9:

https://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame
--
https://mail.python.org/mailman/listinfo/python-list


Re: Learning tkinter - a grid problem

2020-12-07 Thread Terry Reedy

On 12/6/2020 5:59 AM, Terry Reedy wrote:

On 12/6/2020 3:11 AM, Sibylle Koczian wrote:

Am 05.12.2020 um 19:56 schrieb Paulo da Silva:



Why this example does not work?
--
from tkinter import *

root=Tk()
root.geometry("400x200")
S=Scrollbar(root)
T=Text(root)

...

mainloop()



Shouldn't that be
root.mainloop()
?


Yes.  The * import does not turn method into module functions.


But no, sort of.  MRAB is correct that there is (an undocumented) module 
function by the same name.  It calls tkinter._default_root.tk.mainloop 
if _default_root is not None.  This is true if 
tkinter._support_default_root == 1 (the default, but set to 0 in IDLE) 
and tkinter.Tk has been called at least once.


--
Terry Jan Reedy


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


linear algebric equations

2020-12-07 Thread Tito Sanò
Regarding the solution of linear algebraic equations I noticed a big
difference in the computation

time in Python compared to the old fortran language.

I have compared both the linelg and lapack.dgesv-lapack.zgesv modules with
the fortan: dgelg and f04adf. 

The difference in computation time is enormous:

for example for 430 degrees of freedom it is about 24 min in Python versus
about 1 sec in fortran.

Is it possible to get better performance in Python?

Thanks in advance  

Tito Sano’ 

Roma Italy

Cell: 339 6903895

 

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


Re: Letter replacer - suggestions?

2020-12-07 Thread Grant Edwards
On 2020-12-07, MRAB  wrote:

> Avoid a 'bare' except unless you _really_ mean it, which is
> virtually never. Catch only those exceptions that you're going to
> handle.

And sometimes "handling" is just printing some extra stuff and then
re-raising the original exception:

try:
something():
except:
print()
raise


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


RE: Letter replacer - suggestions?

2020-12-07 Thread Schachner, Joseph
The only comment I have is that you didn't check the inputs at all.  Suppose 
the word I type in is "1234".   1234 will turn into an int, not a string.
You can't index through an int, it's one thing.  So the program will probably 
throw an error.

If the word at least starts with a letter, then it will be a string.   If I say 
I want to replace "?" that may not exist in the string, but that's OK. 

 Joseph S. 

-Original Message-
From: Bischoop  
Sent: Monday, December 7, 2020 10:48 AM
To: python-list@python.org
Subject: Letter replacer - suggestions?


I worked on my wee script that replaces a letters: https://bpa.st/OYBQ .
I would like to have some suggestions about the code from more experienced 
programmers, the code does work and do its job but perhaps could work in a 
better way.

Thanks

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


Re: Letter replacer - suggestions?

2020-12-07 Thread Chris Angelico
On Tue, Dec 8, 2020 at 6:41 AM Grant Edwards  wrote:
>
> On 2020-12-07, MRAB  wrote:
>
> > Avoid a 'bare' except unless you _really_ mean it, which is
> > virtually never. Catch only those exceptions that you're going to
> > handle.
>
> And sometimes "handling" is just printing some extra stuff and then
> re-raising the original exception:
>
> try:
> something():
> except:
> print()
> raise
>

Even there, I'd most often use "except BaseException as e:", other
than in a very few situations. The only time I have recently used a
bare except is when making use of the traceback module:

try:
...
except:
with open("notes.err", "a") as err:
traceback.print_exc(file=err)
raise

since print_exc() can go fetch the exception via sys.exc_info().

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


Re: Letter replacer - suggestions?

2020-12-07 Thread Chris Angelico
On Tue, Dec 8, 2020 at 6:51 AM Schachner, Joseph
 wrote:
>
> The only comment I have is that you didn't check the inputs at all.  Suppose 
> the word I type in is "1234".   1234 will turn into an int, not a string.
> You can't index through an int, it's one thing.  So the program will probably 
> throw an error.

Not sure what you mean here. The input() function always returns a
string, even if it's nothing but decimal digits.

(If you're using an ancient version of Python, then it will evaluate
the input, which would mean digits turn into an integer, but other
things will just error out - they won't be strings. Also, all the
f-strings in the OP's code wouldn't work, so that's irrelevant here.)

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


Re: Letter replacer - suggestions?

2020-12-07 Thread inhahe
Besides what others have said (especially re using a dict instead), I think
it's unpythonic/can result in unexpected behavior to change a list as it's
being iterated over. Your modified word_list should be a separate list, I
think.
Also, if you use enumerate(), you won't have to use .index and it would be
more efficient.
And I'm not sure what the 'while True' accomplishes. Seems it would put it
in an endless loop? If the 'while True' were in the beginning of the
program, before the inputs, it would make more sense. (And in that case
you'd probably want to break the loop if `word` is empty)

On Mon, Dec 7, 2020 at 10:51 AM Bischoop  wrote:

>
> I worked on my wee script that replaces a letters: https://bpa.st/OYBQ .
> I would like to have some suggestions about the code from more
> experienced programmers, the code does work and do its job but perhaps
> could work in a better way.
>
> Thanks
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Letter replacer - suggestions?

2020-12-07 Thread Jon Ribbens via Python-list
On 2020-12-07, Chris Angelico  wrote:
> On Tue, Dec 8, 2020 at 6:41 AM Grant Edwards  
> wrote:
>> On 2020-12-07, MRAB  wrote:
>> > Avoid a 'bare' except unless you _really_ mean it, which is
>> > virtually never. Catch only those exceptions that you're going to
>> > handle.
>>
>> And sometimes "handling" is just printing some extra stuff and then
>> re-raising the original exception:
>>
>> try:
>> something():
>> except:
>> print()
>> raise
>>
>
> Even there, I'd most often use "except BaseException as e:", other
> than in a very few situations. The only time I have recently used a
> bare except is when making use of the traceback module:
>
> try:
> ...
> except:
> with open("notes.err", "a") as err:
> traceback.print_exc(file=err)
> raise
>
> since print_exc() can go fetch the exception via sys.exc_info().

... but even if you do think you want "except BaseException:" or
"except:", you almost never actually do - you almost certainly want
"except Exception:", because the former two will stop sys.exit()
from working, or the user from pressing ctrl-C.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Letter replacer - suggestions?

2020-12-07 Thread Chris Angelico
On Tue, Dec 8, 2020 at 7:11 AM Jon Ribbens via Python-list
 wrote:
>
> On 2020-12-07, Chris Angelico  wrote:
> > On Tue, Dec 8, 2020 at 6:41 AM Grant Edwards  
> > wrote:
> >> On 2020-12-07, MRAB  wrote:
> >> > Avoid a 'bare' except unless you _really_ mean it, which is
> >> > virtually never. Catch only those exceptions that you're going to
> >> > handle.
> >>
> >> And sometimes "handling" is just printing some extra stuff and then
> >> re-raising the original exception:
> >>
> >> try:
> >> something():
> >> except:
> >> print()
> >> raise
> >>
> >
> > Even there, I'd most often use "except BaseException as e:", other
> > than in a very few situations. The only time I have recently used a
> > bare except is when making use of the traceback module:
> >
> > try:
> > ...
> > except:
> > with open("notes.err", "a") as err:
> > traceback.print_exc(file=err)
> > raise
> >
> > since print_exc() can go fetch the exception via sys.exc_info().
>
> ... but even if you do think you want "except BaseException:" or
> "except:", you almost never actually do - you almost certainly want
> "except Exception:", because the former two will stop sys.exit()
> from working, or the user from pressing ctrl-C.

For "log and reraise" handlers, actually I usually *do* want to see
those. The goal of these is to report the exception in some different
way from the normal one, and maybe figuring out why some subsystem is
dying inexplicably; and a KeyboardInterrupt would definitely be of
note there.

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


Re: linear algebric equations

2020-12-07 Thread Dan Stromberg
On Mon, Dec 7, 2020 at 11:36 AM Tito Sanò  wrote:

> Regarding the solution of linear algebraic equations I noticed a big
> difference in the computation
>
> time in Python compared to the old fortran language.
>
> I have compared both the linelg and lapack.dgesv-lapack.zgesv modules with
> the fortan: dgelg and f04adf.
>
> The difference in computation time is enormous:
>
> for example for 430 degrees of freedom it is about 24 min in Python versus
> about 1 sec in fortran.
>
> Is it possible to get better performance in Python?
>

Can you make your test code available for examination?

If you are using CPython, are you also using numpy? Or numba?

If you are using pure Python, have you tried Pypy3?

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


list of dictionaries search using kwargs

2020-12-07 Thread Larry Martell
I have a class that has an object that contains a list of dicts. I
want to have a class method that takes a variable number of key/value
pairs and searches the list and returns the item that matches the
arguments.

If I know the key value pairs I can do something like this:

instance = next(item for item in data] if\
   item["appCode"] == 1 and\
   item["componentCode"] == "DB" and\
   item["environmentEnumID"] == 12 and\
   item["serverName"] == 'foo', None)

But in my class method if I have:

def find_data_row(self, **kwargs):

and I call it:

find_data_row(appCode=1, componentCode='DB', ...)

How can I do the search in a pythonic way?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Letter replacer - suggestions?

2020-12-07 Thread Marco Sulla
Not sure why you want to do this (it's schoolwork)? Anyway, this is my version:

word = input('input word you want to change letters in: ')

chars = tuple(word)
change_this = input('Enter the letters you want to change: ')
replace_with = input('Enter the letters to replace with: ')

if len(change_this) != len(replace_with):
raise RuntimeError(
"Letters to replace must be equals in number to letters you want " +
"to change"
)

change_chars = tuple(change_this)
replace_chars = tuple(replace_with)

new_chars = []

for ch in chars:
try:
i = change_chars.index(ch)
except ValueError:
new_chars.append(ch)
else:
new_chars.append(replace_chars[i])
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: list of dictionaries search using kwargs

2020-12-07 Thread Marco Sulla
You can return dictionaries that returns True if

(a.items() & kwargs.items()) == kwargs.items()

when `a` is one of your dicts.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: list of dictionaries search using kwargs

2020-12-07 Thread Larry Martell
On Mon, Dec 7, 2020 at 5:29 PM Marco Sulla  wrote:
>
> You can return dictionaries that returns True if
>
> (a.items() & kwargs.items()) == kwargs.items()
>
> when `a` is one of your dicts.

But what is passed in kwargs will not necessarily have values for all
of the keys and I only want to check for matches with the ones passed
in.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: list of dictionaries search using kwargs

2020-12-07 Thread Matt Wheeler
for item in self.data:
    if all(item[k] == v for k,v in kwargs.items()):
        return item

Or

return [item for item in self.data if all(item[k] == v for k,v in 
kwargs.items())]

to return all matches

Beware though that either of these will be slow if your list of dicts is large.
If the list is large enough that this becomes slow, consider using a database 
(e.g. sqlite or other SQL DB) instead.
On 7 Dec 2020, 22:06 +, Larry Martell , wrote:
> I have a class that has an object that contains a list of dicts. I
> want to have a class method that takes a variable number of key/value
> pairs and searches the list and returns the item that matches the
> arguments.
>
> If I know the key value pairs I can do something like this:
>
> instance = next(item for item in data] if\
> item["appCode"] == 1 and\
> item["componentCode"] == "DB" and\
> item["environmentEnumID"] == 12 and\
> item["serverName"] == 'foo', None)
>
> But in my class method if I have:
>
> def find_data_row(self, **kwargs):
>
> and I call it:
>
> find_data_row(appCode=1, componentCode='DB', ...)
>
> How can I do the search in a pythonic way?
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: list of dictionaries search using kwargs

2020-12-07 Thread Larry Martell
On Mon, Dec 7, 2020 at 5:42 PM Matt Wheeler  wrote:
>
> for item in self.data:
> if all(item[k] == v for k,v in kwargs.items()):
> return item
>
> Or
>
> return [item for item in self.data if all(item[k] == v for k,v in 
> kwargs.items())]
>
> to return all matches
>
> Beware though that either of these will be slow if your list of dicts is 
> large.
> If the list is large enough that this becomes slow, consider using a database 
> (e.g. sqlite or other SQL DB) instead.

Thanks! Works perfectly.

> On 7 Dec 2020, 22:06 +, Larry Martell , wrote:
>
> I have a class that has an object that contains a list of dicts. I
>
> want to have a class method that takes a variable number of key/value
>
> pairs and searches the list and returns the item that matches the
>
> arguments.
>
>
> If I know the key value pairs I can do something like this:
>
>
> instance = next(item for item in data] if\
>
> item["appCode"] == 1 and\
>
> item["componentCode"] == "DB" and\
>
> item["environmentEnumID"] == 12 and\
>
> item["serverName"] == 'foo', None)
>
>
> But in my class method if I have:
>
>
> def find_data_row(self, **kwargs):
>
>
> and I call it:
>
>
> find_data_row(appCode=1, componentCode='DB', ...)
>
>
> How can I do the search in a pythonic way?
>
> --
>
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Error

2020-12-07 Thread Michael Torrie
On 12/7/20 11:30 AM, MRAB wrote:
> There's no need to remove Python 3.9 first; Python 3.8 can be installed 
> alongside it.

Since the original poster is invoking python.exe directly, probably as
per the instructions in the book he's following, I fear having two
versions of python installed will just lead to confusion.  In his case,
I think it's best to just have Python 3.8 installed.  Although
pgzrun.exe will almost certainly execute the correct version of Python,
so probably wouldn't matter either way.

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


Re: list of dictionaries search using kwargs

2020-12-07 Thread MRAB

On 2020-12-07 22:06, Larry Martell wrote:

I have a class that has an object that contains a list of dicts. I
want to have a class method that takes a variable number of key/value
pairs and searches the list and returns the item that matches the
arguments.

If I know the key value pairs I can do something like this:

instance = next(item for item in data] if\
item["appCode"] == 1 and\
item["componentCode"] == "DB" and\
item["environmentEnumID"] == 12 and\
item["serverName"] == 'foo', None)

But in my class method if I have:

 def find_data_row(self, **kwargs):

and I call it:

find_data_row(appCode=1, componentCode='DB', ...)

How can I do the search in a pythonic way?


An item is a match if:

all(item[key] == value for key, value in kwargs.items())

or possibly:

MISSING = object()

all(item.get(key, MISSING) == value for key, value in kwargs.items())

Just iterate over the list of dicts until you find a match.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Letter replacer - suggestions?

2020-12-07 Thread dn via Python-list

word = input('input word you want to change letters in: ')

chars = tuple(word)
change_this = input('Enter the letters you want to change: ')
replace_with = input('Enter the letters to replace with: ')

if len(change_this) != len(replace_with):
 raise RuntimeError(
 "Letters to replace must be equals in number to letters you want " +
 "to change"
 )

change_chars = tuple(change_this)
replace_chars = tuple(replace_with)

new_chars = []

for ch in chars:
 try:
 i = change_chars.index(ch)
 except ValueError:
 new_chars.append(ch)
 else:
 new_chars.append(replace_chars[i])



There are two 'phases' to this program:

1 collecting the input-data, and
2 performing a translation.

The second and third inputs must be the same length - hence the first 
if-condition (above).



Phase 1:

More user-friendly (considerate) ways to do this include:

- (if short strings) input the character-pairs as a unit:-

while ... # decide upon a sentinel/loop-terminator
in = input( "A character and its replacement" )
source_character, replacement_character = in.split( ... )
# insert appropriate criteria as ...
source_list.append( source_character )
replacement_list.append( replacement_character )

- (existing practice) alter the input() "prompt-strings" to be the same 
length, and thus assist the user to *see* that his/her two inputs [must] 
also 'match' in length! eg


Source  characters? abcdef↵
Encoded characters? zyxwuv↵


Phase 2:

The translation phase is most easily achieved with the built-in 
str.translate() - and likely faster! First the translation-table must be 
built, then the source-text(s) translated:


source_str = "".join( source_list )
replacement_str = "".join( replacement_list )
# have to join (above) lists into strings for next line
translation_table = str.maketrans( source_str, replacement_str )
translation = word.translate( translation_table )

NB because maketrans() is a static method (of the str[ing] class) we 
must use the "str.".


NBB because str.maketrans() checks the length of the two 
translation-strings, wrapping that with try...except might be considered 
more 'pythonic' than the "first if-condition" (although "explicit is 
better...", Zen of Python)



For extra credit/re-factoring further:
(after learning the above 'straight-line' approaches and code constructs)

str.maketrans() will accept a single dict[ionary]. Accordingly, instead 
of collecting the translation data as two lists - which must then be 
converted into strings; (no matter which approach to 'phase 1' is 
preferred); consider building a translation-dictionary wherein each 
entry has the 'letter to be changed' as its "key", and its "data" is 
'the letter to replace [it] with'. Refactoring from the above:


source_character, replacement_character = in.split( ... )
translation_dict[ source_character ] = replacement_character
translation_table = str.maketrans( translation_dict )
translation = word.translate( translation_table )


Trust this adds to your 'adventures' in learning Python!


Web.Refs:
https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str
https://www.askpython.com/python/string/python-string-translate
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Letter replacer - suggestions?

2020-12-07 Thread Marco Sulla
On Tue, 8 Dec 2020 at 00:10, dn via Python-list  wrote:
> The translation phase is most easily achieved with the built-in
> str.translate()

I forgot it :-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: list of dictionaries search using kwargs

2020-12-07 Thread Marco Sulla
On Mon, 7 Dec 2020 at 23:35, Larry Martell  wrote:
>
> On Mon, Dec 7, 2020 at 5:29 PM Marco Sulla  
> wrote:
> >
> > You can return dictionaries that returns True if
> >
> > (a.items() & kwargs.items()) == kwargs.items()
> >
> > when `a` is one of your dicts.
>
> But what is passed in kwargs will not necessarily have values for all
> of the keys

That's why I used the operator `&`. Anyway you already made your choice :-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Letter replacer - suggestions?

2020-12-07 Thread dn via Python-list

On 08/12/2020 12:15, Marco Sulla wrote:

On Tue, 8 Dec 2020 at 00:10, dn via Python-list  wrote:

The translation phase is most easily achieved with the built-in
str.translate()


I forgot it :-)



That's down to the rich-ness of the Python eco-system!

IIRC (from previous posts) the OP is teaching him-/her-self Python. 
Thus, learning one-step at a time, building complexity in-line with 
confidence, is the way (s)he's going. Accordingly, each answer, building 
on the previous shows the way forward (as well as, the process of 
re-factoring)!


BTW his/her learn-by-doing approach is also the reason why I didn't 
write a complete-code answer.



Interestingly (at least, to me), the earlier response was me taking a 
break from writing a short paper (nothing-much to do with Python). 
Herewith some overlap of ideas:-


The aphorism claiming "two heads are better than one" is also the basis 
for what business-groups commonly call "brain-storming" (or 
"spit-balling", if you're 'in' marketing). However, did you know that 
"brain-storming" (in-person) seldom reaches the aspiration of finding 
'the best possible answer'?


Further, that if team-members work remotely, (first) 'attacking' a 
problem individually, and only after that, pooling their ideas to 
produce a plan; the chosen 'answer' will (likely) be much better!


Reasons: stated opinion of the "highest paid [wo]man in the room", 
dominant personalities, extrovert behavior, introvert behavior, I'd 
rather be sailing, ...


Thus: "Planning Poker" as a 'bottom-up', Agile, method for story/task 
(length) estimation!

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


[RELEASE] Python 3.9.1 is now available, together with 3.10.0a3 and 3.8.7rc1

2020-12-07 Thread Pablo Galindo Salgado
It's starting to get very cold (at least on the Northern hemisphere) so we
have been carefully packaging a total of three new Python releases to keep
you warm these days!

Python 3.9.1 is the first maintenance release of Python 3.9, and also the
first version of Python to support macOS 11 Big Sur natively on Apple
Silicon. Go get it here:

https://www.python.org/downloads/release/python-391/

Maintenance releases for the 3.9 series will continue at regular bi-monthly
intervals, with **3.9.2** planned for Monday, 2021-02-08.

Python 3.10a3 is the third alpha release of Python 3.10. You can get it
here:

https://www.python.org/downloads/release/python-3100a3/

Python 3.10a3 is the release preview of the next maintenance release of
Python 3.8. You can get it here:

https://www.python.org/downloads/release/python-387rc1/

Assuming no critical problems are found prior to **2020-12-21** , the
currently scheduled release date for **3.8.7** , no code changes are
planned between this release candidate and the final release. That being
said, please keep in mind that this is a pre-release of 3.8.7 and as such
its main purpose is testing.

Your friendly release team,
Ned Deily, Steve Dower, Pablo Galindo, Łukasz Langa
-- 
https://mail.python.org/mailman/listinfo/python-list