asyncio question
Hi all My app runs an HTTP server using asyncio. A lot of the code dates back to Python 3.4, and I am trying to bring it up to date. There is one aspect I do not understand. The 'old' way looks like this - import asyncio def main(): loop = asyncio.get_event_loop() server = loop.run_until_complete( asyncio.start_server(handle_client, host, port)) loop.run_forever() if __name__ == '__main__': main() According to the docs, the preferred way is now like this - import asyncio async def main(): loop = asyncio.get_running_loop() server = await asyncio.start_server( handle_client, host, port) async with server: server.serve_forever() if __name__ == '__main__': asyncio.run(main()) It works, and it does look neater. But I want to start some background tasks before starting the server, and cancel them on Ctrl+C. Using the 'old' method, I can wrap 'loop.run_forever()' in a try/except/finally, check for KeyboardInterrupt, and run my cleanup in the 'finally' block. Using the 'new' method, KeyboardInterrupt is not caught by 'server.serve_forever()' but by 'asyncio.run()'. It is too late to do any cleanup at this point, as the loop has already been stopped. Is it ok to stick to the 'old' method, or is there a better way to do this. Thanks Frank Millman -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 2020-11-03, dn wrote: > > > The (full) specs are not clear. There's certainly room for > misunderstanding. I'd be happier if I could 'see' a full spec or > recognise a practical application, because then we'd be better able to > discuss facts. Meantime, we try to help with what we have been given... > > > The OP's sample code only realises "conforming word[s]" (good term > BTW!). The snippet does not report any "count". Similarly, there's no > facts to avoid ("I assume") an assumption about whether "Letters" may > include duplication - indeed: whether duplication has meaning or should > be regarded as user-error. > Let me clarify what I want to do: We all know Scrabble game. there's a file with Dictionary containing word in each line, the idea is to input some letters for example mentioned earlier: att, the script supposed to find all words in which letters: 'a','t','t' occur and print these words. It supposed not to print word: 'auto' because there's only one 't' but words such as: 'toast', 'toasty', 'tolerant' are meeting the criteria becase we have in these words one 'a' and two 't' as user has input. I've checked collections counter but seems to complicated for me at this stage yet and I'm struggling with applying it. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
Bischoop writes: > Let me clarify what I want to do: > We all know Scrabble game. > there's a file with Dictionary containing word in each line, the idea is > to input some letters for example mentioned earlier: att, the script > supposed to find all words in which letters: 'a','t','t' occur and print > these words. It supposed not to print word: 'auto' because there's only > one 't' but words such as: 'toast', 'toasty', 'tolerant' are meeting the > criteria becase we have in these words one 'a' and two 't' as user has > input. In Scrabble, you will usually know the order you want for the known letters, so you could just make a regular expression: t.*a.*t In fact, you often know the gaps, so you might even be able to match something more specific like t.a..t instead. If you don't know the order, you can still make a chain of matches. For example, matching for t.*t and then also a. Every distinct letter needs a match, and repeated letters need a single match with .* between them. And since Python REs have (?=...) look ahead syntax you could even make a single pattern like this: (?=.*t.*t)(?=.*a) While there are probably better ways in Python, this is what I'd do on the command line. For example $ grep -P '(?=.*t.*t)(?=.*a)' word-list | wc -l 45677 $ grep 't.*t' word-list | grep a | wc -l 45677 -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
Please help test astral char display in tkinter Text (especially *nix)
tcl/tk supports unicode chars in the BMP (Basic Multilingual Plane, utf-8 encoded with 1-3 bytes). The presence of chars in other plains ('astral', utf-8 encoded with 4 bytes, I believe) in a tkinter Text widget messages up *editing*, but they can sometimes be displayed with appropriate glyphs. On my Windows 10 64-bit 2004 update, astral code points print as unassigned [X], replaced [], or proper glyphs (see below). On my up-to-date macOS Mohave, as far as I know, no glyphs are actually printed and some hang, freezing IDLE's Shell (and making extensive testing difficult). On Linux, behavior is mixed, including 'crashes', with the use of multicolor rather than black/white fonts apparently an issue. https://bugs.python.org/issue42225. I would like more information about behavior on other systems, especially *nix. The following runs to completion for me, without errors, in about 1 second. tk = True if tk: from tkinter import Tk from tkinter.scrolledtext import ScrolledText root = Tk() text = ScrolledText(root, width=80, height=40) text.pack() def print(txt): text.insert('insert', txt+'\n') errors = [] for i in range(0x1, 0x4, 32): chars = ''.join(chr(i+j) for j in range(32)) try: print(f"{hex(i)} {chars}") except Exception as e: errors.append(f"{hex(i)} {e}") print("ERRORS:") for line in errors: print(line) Perhaps half of the assigned chars in the first plane are printed instead of being replaced with a narrow box. This includes emoticons as foreground color outlines on background color. Maybe all of the second plane of extended CJK chars are printed. The third plane is unassigned and prints as unassigned boxes (with an X). If you get errors, how many. If you get a hang or crash, how far did the program get? -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Best way to determine user's screensize?
On Sun, 1 Nov 2020 15:31:57 - (UTC), Grant Edwards wrote: > > I have no objection to saving the most recent window size and using > that on the next startup, but I hate applications that force the > _location_ of the window. I've configured my window manager to open > windows where I want them opened, please respect that. Hear, hear! This user has invested a lot of time learning how to live comfortably with his window manager. When some upstart app invalidates that knowledge and the corresponding deeply ingrained habits, it's a big annoyance. -- To email me, substitute nowhere->runbox, invalid->com. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 03/11/2020 14:06, Bischoop wrote: > On 2020-11-03, dn wrote: >> >> >> The (full) specs are not clear. There's certainly room for >> misunderstanding. I'd be happier if I could 'see' a full spec or >> recognise a practical application, because then we'd be better able to >> discuss facts. Meantime, we try to help with what we have been given... >> >> >> The OP's sample code only realises "conforming word[s]" (good term >> BTW!). The snippet does not report any "count". Similarly, there's no >> facts to avoid ("I assume") an assumption about whether "Letters" may >> include duplication - indeed: whether duplication has meaning or should >> be regarded as user-error. >> > > Let me clarify what I want to do: > We all know Scrabble game. > there's a file with Dictionary containing word in each line, the idea is > to input some letters for example mentioned earlier: att, the script > supposed to find all words in which letters: 'a','t','t' occur and print > these words. It supposed not to print word: 'auto' because there's only > one 't' but words such as: 'toast', 'toasty', 'tolerant' are meeting the > criteria becase we have in these words one 'a' and two 't' as user has > input. > I've checked collections counter but seems to complicated for me at this > stage yet and I'm struggling with applying it. > >>> from collections import Counter >>> letters = 'att' >>> letter_counts = Counter(letters) >>> word = 'tolerate' >>> wd_counts = Counter(word) >>> for char, cnt in letter_counts.items(): print (cnt == wd_counts[char]) True True >>> word = 'auto' >>> wd_counts = Counter(word) >>> for char, cnt in letter_counts.items(): print (cnt == wd_counts[char]) True False >>> or, equivalent to the above loop, but breaking when the first False is generated and returning the single Boolean that you're after, >>> all(cnt == wd_counts[char] for char, cnt in letter_counts.items()) False >>> There's still a lot of scope for improvement, but possibly not by doing simple things. Duncan -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On Wed, Nov 4, 2020 at 1:11 AM Bischoop wrote: > Let me clarify what I want to do: > We all know Scrabble game. > there's a file with Dictionary containing word in each line, the idea is > to input some letters for example mentioned earlier: att, the script > supposed to find all words in which letters: 'a','t','t' occur and print > these words. It supposed not to print word: 'auto' because there's only > one 't' but words such as: 'toast', 'toasty', 'tolerant' are meeting the > criteria becase we have in these words one 'a' and two 't' as user has > input. > I've checked collections counter but seems to complicated for me at this > stage yet and I'm struggling with applying it. This seems strangely backwards for a Scrabble game. Normally you would have a set of available tiles, and you have to form a word using only those tiles, but it doesn't necessarily have to use them all. You seem to have something where you must use all the tiles you have, and may use any number of others. But, no matter; it can be done either way. >>> from collections import Counter >>> Counter("att") <= Counter("toast") True >>> Counter("att") <= Counter("toasty") True >>> Counter("att") <= Counter("tolerant") True >>> Counter("att") <= Counter("auto") False A Counter can behave like a multiset. If you picture the <= operator as being "is a subset of", and then squint a little, irritate your math teacher, and pretend that a set can have more than one of the same thing in it, then a Counter's less-than-or-equal operator will tell you if one multiset is a subset of another. (The normal way to play Scrabble would simply reverse the operands, so you'd ask if the word is <= the tiles you have. It's otherwise exactly the same check.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Solaris 11 GUI framework
On 2020-11-02, Igor Korot wrote: > On Mon, Nov 2, 2020, 3:57 PM Jay Braun wrote: > >> Looking for a GUI framework supported on Solaris 11. > > Wxpython, pygtk, Java. I wouldn't start a new project with pygtk. It's obsolete (Python2 only) and is no longer supported/available on some platforms. It's been replace by PyGObject https://pygobject.readthedocs.io/en/latest/ Porting from PyGtk to PyGObject is pretty straight-forward, but PyGObject is definitely less "Pythonic". While PyGtk was a hand-crafted set of python bindings for GTK2, PyGObject is sort-of automated based on the standard introspection features of GObject libraries. I've heard this requires a lot less maintenance than the old PyGTK bindings. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Fwd: [RELEASE] Python 3.10.0a2 available for testing
The engines of the secret release manager machine have finished producing a new pre-release. Go get it here: https://www.python.org/downloads/release/python-3100a2/ *Major new features of the 3.10 series, compared to 3.9* Python 3.10 is still in development. This releasee, 3.10.0a2 is the second of six planned alpha releases. Alpha releases are intended to make it easier to test the current state of new features and bug fixes and to test the release process. During the alpha phase, features may be added up until the start of the beta phase (2021-05-03) and, if necessary, may be modified or deleted up until the release candidate phase (2021-10-04). Please keep in mind that this is a preview release and its use is not recommended for production environments. Many new features for Python 3.10 are still being planned and written. Among the new major new features and changes so far: PEP 623 -- Remove wstr from Unicode PEP 604 -- Allow writing union types as X | Y PEP 612 -- Parameter Specification Variables PEP 626 -- Precise line numbers for debugging and other tools. (Hey, fellow core developer, if a feature you find important is missing from this list, let Pablo know.) The next pre-release of Python 3.10 will be 3.10.0a3, currently scheduled for 2020-12-07. *And now for something completely different * The cardinality (the number of elements) of infinite sets can be one of the most surprising results of set theory. For example, there are the same amount of even natural numbers than natural numbers (which can be even or odd). There is also the same amount of rational numbers than natural numbers. But on the other hand, there are more real numbers between 0 and 1 than natural numbers! All these sets have infinite cardinality but turn out that some of these infinities are bigger than others. These infinite cardinalities normally are represented using aleph numbers. Infinite sets are strange beasts indeed. Regards from cold London, Pablo Galindo Salgado -- https://mail.python.org/mailman/listinfo/python-list
Re: Post request and encoding
Hernán De Angelis wrote at 2020-11-2 10:06 +0100: > ... >My request has the form: > >header = {'Content-type':'application/xml', 'charset':'utf-8'} Not your problem (which you have already resolved) but: `charset` is not an individual header but a parameter for the `Content-Type` header. For `xml` `utf-8` is the default charset. -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange terminal behavior after quitting Tkinter application
On Wednesday, April 18, 2007 at 12:33:24 AM UTC-7, Chris wrote: > Hi, > I'm puzzled by some strange behavior when my Python/Tkinter > application quits (on linux): the terminal from which I started Python > is messed up. > If start up python, then import the code below, then start the program > with Application(), then click the Quit button, my terminal never > prints anything again (such as commands I type). > > import Tkinter > import sys > class Application(Tkinter.Tk): > def __init__(self,**config): > Tkinter.Tk.__init__(self,**config) > > Tkinter.Button(self,text="Quit",command=self.quit_application).pack() > def quit_application(self): > sys.exit() > > > Can anyone tell me what I'm doing wrong? > Thanks for your help. > Chris I notice this same behavior with other tk applications like "tkdiff". So what is the correct cleanup for a proper exit from a plain Tk application? -- https://mail.python.org/mailman/listinfo/python-list
RE: Find word by given characters
I, too, have wondered what exactly the point was of the required functionality for SCRABBLE but note you can extend a current word so additional letters may be available in a game but only if they are an exact fit to put before, after, or in middle of your word. But this seems to be a fairly simple problem to solve unless I misunderstand it. Elegance aside, what would be wrong with this approach. - Read a word at a time in a loop from the file of dictionary words (non-Python meaning of dictionary.) For each one do the following, perhaps using a function: Break the current word into a list of individual letters. Loop over the letters you want and: If the letter is in the list, remove it and continue Else skip the current word as it is not a match. At the end of each of the above loops, you only reached here if all the letters were found and removed. If the list is now empty, fine. If it has extra remaining letters, also fine by the requirements stated. Letters in the list multiple times are removed multiple times. The above need not use list of letters and can be done many other ways but seems conceptually simple. Each word is processed once. It can be converted to using a list comprehension or something similar by using "all" and so on. Or am I missing something about other approaches being better or more efficient or ... And, yes, counting may have an advantage as the list does not need to be modified repeatedly but creating an object or three also has overhead. -Original Message- From: Python-list On Behalf Of Chris Angelico Sent: Tuesday, November 3, 2020 12:35 PM To: Python Subject: Re: Find word by given characters On Wed, Nov 4, 2020 at 1:11 AM Bischoop wrote: > Let me clarify what I want to do: > We all know Scrabble game. > there's a file with Dictionary containing word in each line, the idea > is to input some letters for example mentioned earlier: att, the > script supposed to find all words in which letters: 'a','t','t' occur > and print these words. It supposed not to print word: 'auto' because > there's only one 't' but words such as: 'toast', 'toasty', 'tolerant' > are meeting the criteria becase we have in these words one 'a' and two > 't' as user has input. > I've checked collections counter but seems to complicated for me at > this stage yet and I'm struggling with applying it. This seems strangely backwards for a Scrabble game. Normally you would have a set of available tiles, and you have to form a word using only those tiles, but it doesn't necessarily have to use them all. You seem to have something where you must use all the tiles you have, and may use any number of others. But, no matter; it can be done either way. >>> from collections import Counter >>> Counter("att") <= Counter("toast") True >>> Counter("att") <= Counter("toasty") True >>> Counter("att") <= Counter("tolerant") True >>> Counter("att") <= Counter("auto") False A Counter can behave like a multiset. If you picture the <= operator as being "is a subset of", and then squint a little, irritate your math teacher, and pretend that a set can have more than one of the same thing in it, then a Counter's less-than-or-equal operator will tell you if one multiset is a subset of another. (The normal way to play Scrabble would simply reverse the operands, so you'd ask if the word is <= the tiles you have. It's otherwise exactly the same check.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 2020-11-03, Chris Angelico wrote: > > This seems strangely backwards for a Scrabble game. Normally you would > have a set of available tiles, and you have to form a word using only > those tiles, but it doesn't necessarily have to use them all. You seem > to have something where you must use all the tiles you have, and may > use any number of others. But, no matter; it can be done either way. > I know, it's useless I just came to idea to do something when was learning, now I remembered long time ago I've done it somehow with list and len() probably, this time I came to idea to rewrite using count. But it seems I'm crap and takes me hell a lot of time to get on it. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 2020-11-03, duncan smith wrote: >> > from collections import Counter letters = 'att' letter_counts = Counter(letters) word = 'tolerate' wd_counts = Counter(word) for char, cnt in letter_counts.items(): > print (cnt == wd_counts[char]) > > > True > True word = 'auto' wd_counts = Counter(word) for char, cnt in letter_counts.items(): > print (cnt == wd_counts[char]) > > > True > False > > or, equivalent to the above loop, but breaking when the first False is > generated and returning the single Boolean that you're after, > all(cnt == wd_counts[char] for char, cnt in letter_counts.items()) > False > > There's still a lot of scope for improvement, but possibly not by doing > simple things lol I'm thinking about it for a couple days and you guys coming with few ideas to it like it's nothing. Pity I've wasted a decade with woman, now probably to old to learn anything new. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 04/11/2020 12:27, Bischoop wrote: On 2020-11-03, Chris Angelico wrote: This seems strangely backwards for a Scrabble game. Normally you would have a set of available tiles, and you have to form a word using only those tiles, but it doesn't necessarily have to use them all. You seem to have something where you must use all the tiles you have, and may use any number of others. But, no matter; it can be done either way. I know, it's useless I just came to idea to do something when was learning, now I remembered long time ago I've done it somehow with list and len() probably, this time I came to idea to rewrite using count. But it seems I'm crap and takes me hell a lot of time to get on it. Don't beat yourself up about it. As you have already noted, it is difficult for an 'apprentice' to know things (s)he has yet to learn - and that was related to Python-language features. On top of that, it is another difficult and quite different skill to write a specification which is accurate, complete, and meaningful to coders... Do I recall that you are 'coming back' to Python, and as an hobbyist? Rather than setting your own specs, why not work from those set by others? If you want to learn the Python language, and especially if you also mean 'programming' as an art?science, why not add some structure and follow a text-book or an on-line course? For example, Dr Chuck's (famous and long-standing) courses and other U.Mich offerings are available from https://www.coursera.org/search?query=python&; (624 'hits'!). You will find similar (perhaps I notice a DataScience/ML bias?) on edx.org (https://www.edx.org/search?q=python&tab=course) Your thoughts? Disclaimer: I train from the edX platform - but not in Python. -- Regards =dn -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange terminal behavior after quitting Tkinter application
On 2020-11-03 20:11, David Burnette wrote: On Wednesday, April 18, 2007 at 12:33:24 AM UTC-7, Chris wrote: Hi, I'm puzzled by some strange behavior when my Python/Tkinter application quits (on linux): the terminal from which I started Python is messed up. If start up python, then import the code below, then start the program with Application(), then click the Quit button, my terminal never prints anything again (such as commands I type). import Tkinter import sys class Application(Tkinter.Tk): def __init__(self,**config): Tkinter.Tk.__init__(self,**config) Tkinter.Button(self,text="Quit",command=self.quit_application).pack() def quit_application(self): sys.exit() Can anyone tell me what I'm doing wrong? Thanks for your help. Chris I notice this same behavior with other tk applications like "tkdiff". So what is the correct cleanup for a proper exit from a plain Tk application? Updated to Python 3, it should be more like this: import tkinter import sys class Application(tkinter.Tk): def __init__(self,**config): tkinter.Tk.__init__(self, **config) tkinter.Button(self, text="Quit", command=self.quit_application).pack() def quit_application(self): self.destroy() Application().mainloop() -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 03/11/2020 23:35, Bischoop wrote: > On 2020-11-03, duncan smith wrote: >>> >> > from collections import Counter > letters = 'att' > letter_counts = Counter(letters) > word = 'tolerate' > wd_counts = Counter(word) > for char, cnt in letter_counts.items(): >> print (cnt == wd_counts[char]) >> >> >> True >> True > word = 'auto' > wd_counts = Counter(word) > for char, cnt in letter_counts.items(): >> print (cnt == wd_counts[char]) >> >> >> True >> False > >> >> or, equivalent to the above loop, but breaking when the first False is >> generated and returning the single Boolean that you're after, >> > all(cnt == wd_counts[char] for char, cnt in letter_counts.items()) >> False > >> >> There's still a lot of scope for improvement, but possibly not by doing >> simple things > > > lol > > I'm thinking about it for a couple days and you guys coming with few > ideas to it like it's nothing. > Pity I've wasted a decade with woman, now probably to old to learn > anything new. > It looks like you've learnt something about wasting time with women ;-). Keep tinkering as long as you're enjoying it (or getting paid for it) and pick up knowledge of relevant data structures and algorithms as you go. (That's what I've done. I'm actually a statistician.) The above solution uses bags (implemented in Python as Counter instances), and the (repeated) generation of the letters bag was hoisted outside the for loop. (If the dictionary was going to be searched for multiple sets of letters the generation of the word bags would also be hoisted.) There's also the idea of breaking out of the loop once the first False is generated (implemented most neatly by using all). So there might be something useful to take from it. A bag was the obvious data structure because the solution depends only on the unique characters in a string and their frequencies. But that's thinking about the problem word by word. We actually have a dictionary of words, and a dictionary can be structured so that it can be searched much more efficiently than 'word by word'. The particular data structure I have in mind is not (yet) in the standard Python library. That's maybe worth looking at when you've got the word by word approach grokked. Duncan -- https://mail.python.org/mailman/listinfo/python-list
Help
So, I'm newer to Python and I'm messing around with math functions and multiplication, etc. here is my line of code: def multiply(numbers): total = 1 for x in numbers: total *= x return total print(multiply((8, 2, 3, -1, 7))) When I run this, my answer is 8 but it should be 336 can some help ._. -- https://mail.python.org/mailman/listinfo/python-list
Re: Help
> > When I run this, my answer is 8 but it should be 336 can some help ._. > Looks like you are returning from inside the loop. Skip > -- https://mail.python.org/mailman/listinfo/python-list
Re: Help
On 2020-11-04, Quentin Bock wrote: > So, I'm newer to Python and I'm messing around with math functions and > multiplication, etc. here is my line of code: > > def multiply(numbers): > total = 1 > for x in numbers: > total *= x > return total > print(multiply((8, 2, 3, -1, 7))) > > When I run this, my answer is 8 but it should be 336 can some help ._. 1. If you're using tabs to indent; don't. It results in hard-to diagnose problems. Use spaces to indent. 2. Cut/past the exact code when asking questions. The code you posted does not print 8. It doesn't run at all: $ cat bar.py def multiply(numbers): total = 1 for x in numbers: total *= x return total print(multiply((8, 2, 3, -1, 7))) $ python bar.py File "bar.py", line 3 for x in numbers: ^ IndentationError: unexpected indent 3. The answer you want is not 336, it's -336: $ cat foo.py def multiply(numbers): total = 1 for x in numbers: total *= x return total print(multiply((8,2,3,-1,7))) $ python foo.py -336 4. I suspect that your actual code looks like this: $ cat foo.py def multiply(numbers): total = 1 for x in numbers: total *= x return total print(multiply((8,2,3,-1,7))) $ python foo.py 8 See the difference between #3 and #4? -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 03/11/2020 22:14, Avi Gross wrote: > I, too, have wondered what exactly the point was of the required > functionality for SCRABBLE but note you can extend a current word so > additional letters may be available in a game but only if they are an exact > fit to put before, after, or in middle of your word. > > But this seems to be a fairly simple problem to solve unless I misunderstand > it. Elegance aside, what would be wrong with this approach. > > - Read a word at a time in a loop from the file of dictionary words > (non-Python meaning of dictionary.) For each one do the following, perhaps > using a function: > > Break the current word into a list of individual letters. > Loop over the letters you want and: > If the letter is in the list, remove it and continue > Else skip the current word as it is not a match. > > At the end of each of the above loops, you only reached here if all the > letters were found and removed. If the list is now empty, fine. If it has > extra remaining letters, also fine by the requirements stated. Letters in > the list multiple times are removed multiple times. > > The above need not use list of letters and can be done many other ways but > seems conceptually simple. Each word is processed once. It can be converted > to using a list comprehension or something similar by using "all" and so on. > > Or am I missing something about other approaches being better or more > efficient or ... And, yes, counting may have an advantage as the list does > not need to be modified repeatedly but creating an object or three also has > overhead. [snip] The Counter approach only requires iterating over the letters once to construct the letters bag, then each word once to create the relevant word bag. After that it's (at worst) a couple of lookups and a comparison for each unique character in letters (for each word). Your approach requires iteration over the words to create the lists of characters. Then they are (potentially) iterated over multiple times looking for the characters in letters. There's also the cost of removing items from arbitrary positions in the lists. Also, it seems that the character frequencies must be equal, and your approach only ensures that the words contain at least the required numbers of characters. In computational terms, if the first approach is something like O(n+m) for n letters and words of length m, your algorithm is more like O(nm). Not to say that it will be slower for all possible letters and dictionaries, but probably for any realistic cases and a lot slower for large enough dictionaries. Duncan -- https://mail.python.org/mailman/listinfo/python-list
RE: Find word by given characters
Duncan, my comments below yours at end. ---YOURS--- The Counter approach only requires iterating over the letters once to construct the letters bag, then each word once to create the relevant word bag. After that it's (at worst) a couple of lookups and a comparison for each unique character in letters (for each word). Your approach requires iteration over the words to create the lists of characters. Then they are (potentially) iterated over multiple times looking for the characters in letters. There's also the cost of removing items from arbitrary positions in the lists. Also, it seems that the character frequencies must be equal, and your approach only ensures that the words contain at least the required numbers of characters. In computational terms, if the first approach is something like O(n+m) for n letters and words of length m, your algorithm is more like O(nm). Not to say that it will be slower for all possible letters and dictionaries, but probably for any realistic cases and a lot slower for large enough dictionaries. Duncan --MINE--- I appreciate your analysis. I have not looked at the "counter" implementation and suspect it does some similar loops within, albeit it may be implemented in a compiled language like C++. I did not write out my algorithm in Python but have done it for myself. It runs fast enough with most of the time spent in the slow I/O part. We can agree all algorithms have to read in all the words in a data file. There may be ways to store the data such as in a binary tree and even ways to thus prune the search as once a node is reached where all required letters have been found, all further words qualify below that point. If you match say "instant" then instants and instantiation would be deeper in the tree and also qualify assuming extra letters are allowed. We may differ on the requirement as I think that the number of repeats for something like a,t,t require to be at least as big as in "attend" but that "attention" with yet another "t" would also be OK. If I am wrong, fine, but I note the person requesting this has admitted a certain lack of credentials while also claiming he made up a scenario just for fun. So this is not actually a particularly worthy challenge let alone with a purpose. My impression is that the average word length would be something small like 5-7. The number of words in a dictionary might be 100,000 or more. So if you want efficiency, where do you get the bang for the buck? I would argue that a simple test run on all the words might often narrow the field to a much smaller number of answers like just a few thousand or even much less. Say you test for the presence of "aeiou" in words, in whatever order. That might be done from reading a file and filtering out a relatively few potential answers. You can save those for second round to determine if they are fully qualified by any additional rules that may involve more expensive operations. How fast (or slow) are regular expressions for this purpose? Obviously it depends on complexity and something like "^[^aeiou]*[aeiou] [^aeiou]*[aeiou] [^aeiou]*[aeiou] [^aeiou]*[aeiou] [^aeiou]*[aeiou] [^aeiou]*$" would be easy to construct once but likely horribly inefficient in searching and a bit of overkill here. I suspect there is already some simple C function that could be used from within python that looks like findall(choices, word) that might return how many of the letters in choices were found in word and you simply comparer that to length(word) perhaps more efficiently. It looks easier to check if a character exists in one of the ways already discussed within python using a loop as discussed. Something as simple as this: needed = "aeiou" trying = "education" found = all([trying.find(each) >= 0 for each in needed ]) print(found) trying = "educated" found = all([trying.find(each) >= 0 for each in needed ]) print(found) The above prints My point is you can use the above to winnow down possible answers and only subject that smaller number to one of many tests including using a counter, making a dictionary you can query (albeit probably slower for fairly short words) and so on. Back to your other point, you suggest iterating over characters ( I happened to do it in a list) multiple times can result in duplication as the same characters are searched repeatedly. Sure. I simply note most words are short. How much overhead is there searching for say nine characters five times? Compare that to say creating a dictionary or other data structure once, and then making a hash out of each letter being searched for? I can envision many possible ways to speed this up but many involve more use of memory or all other kinds of overhead such as initializing an object and calling various member functions and then deleting it or re-initializing it. My suggestion of removing items from a short list is not ideal and depending on how a bag was otherwise implemented, I could see it being better but a
Re: Strange terminal behavior after quitting Tkinter application
Am 03.11.20 um 23:34 schrieb Dennis Lee Bieber: Out of curiosity, does Python on Linux honor the .pyw extension? On Windows, .pyw indicates a Python program that implements a GUI and will NOT make use of console (stdin/stdout/stderr). On Linux, there is no such distinction. On Windows it is only needed because, if you connect stdin/out, a terminal window pops up. >For a true GUI program that is notr acceptable, the user will be puzzled what this ugly useless window wants to do, and therefore a flag in the EXE file format indicates to Windows if it should pop up the console or not. On Linux, stdin/out is always connected. You must run your program from a terminal window to see it, otherwise it is silently connected to some channel in the background by the desktop environment. It can happen that the standard channels are closed, if you run a program in the terminal and then close the terminal (which sends SIGHUP to the program). In this case the program might later on throw I/O errors, when printing to stdout. Christian -- https://mail.python.org/mailman/listinfo/python-list
Re: asyncio question
On Tue, Nov 3, 2020 at 3:27 AM Frank Millman wrote: > It works, and it does look neater. But I want to start some background > tasks before starting the server, and cancel them on Ctrl+C. > > Using the 'old' method, I can wrap 'loop.run_forever()' in a > try/except/finally, check for KeyboardInterrupt, and run my cleanup in > the 'finally' block. > > Using the 'new' method, KeyboardInterrupt is not caught by > 'server.serve_forever()' but by 'asyncio.run()'. It is too late to do > any cleanup at this point, as the loop has already been stopped. > > Is it ok to stick to the 'old' method, or is there a better way to do this. > It's fine to stick with the older method in your case, as there's nothing inherently wrong with continuing to use it. `asyncio.run()` is largely a convenience function that takes care of some finalization/cleanup steps that are often forgotten (cancelling remaining tasks, closing event loop's default ThreadPoolExecutor, closing async generators, etc). If you want to use custom KeyboardInterrupt handling and still use asyncio.run(), you can either (a) use `loop.add_signal_handler()` or (b) make a slightly modified local version of `asyncio.run()` that has your desired KeyboardInterrupt behavior, based roughly on https://github.com/python/cpython/blob/master/Lib/asyncio/runners.py. However, using `loop.run_until_complete()` instead of `asyncio.run()` is also perfectly fine, especially in existing code that still works without issue. It just leaves the author with a bit more responsibility when it comes to resource finalization and dealing with the event loop in general (which can add some extra cognitive burden and room for error, particularly when dealing with multiple event loops or threads). But it's reasonably common to continue using `loop.run_until_complete()` in situations where the default `asyncio.run()` behavior isn't what you need/want, such as your case. -- https://mail.python.org/mailman/listinfo/python-list
Re: Post request and encoding
I see. Should be "encoding". Thanks. /H. On 2020-11-03 19:30, Dieter Maurer wrote: Hernán De Angelis wrote at 2020-11-2 10:06 +0100: ... My request has the form: header = {'Content-type':'application/xml', 'charset':'utf-8'} Not your problem (which you have already resolved) but: `charset` is not an individual header but a parameter for the `Content-Type` header. For `xml` `utf-8` is the default charset. -- https://mail.python.org/mailman/listinfo/python-list