For regular non-reversed dunders, the docs say "If one of those methods does not support the operation with the supplied arguments, it should return NotImplemented." (docs.python.org/3/reference/datamodel.html#object.__or__)
One might expect that this also applies to reversed dunders
@Sam How many items would you typically be summing? What actually happens when you add two class instances? sum might get very inefficient when summing a large list, which is why sum won't let you pass it a list of strings to concatenate.
Ah, the type hierarchy confirms this higher up in the page. "Numeric methods and rich comparison methods should return [NotImplemented] if they do not implement the operation for the operands provided"
Yes, yes, multiple string concatenation is catastrophically slow and we should all use .join. Unclear whether Sam's actual class has anything to do with strings at all.
I wonder if shuttles are designed with lightning protection features or if lightning just naturally passes harmlessly along the hull without going through the interior, or what
Relatedly, today's pet peeve is people spelling it "lightening"
That's one of those mistakes that spellcheck can't save you from
At least "loose" and "lose" can be the same part of speech, so sometimes one can substitute for the other.
"We can't get into the house as long as those watchdogs are in the garden", said burglar Alice to burglar Bob. "Open the gates so we can (lose|loose) those hounds"
I suppose lightening can be a noun too, so the same trick can be applied there. "The cargo bay doors opened and the heavy boxes fell out into the roiling storm clouds. Pilot Carol was thrown-off balance by the sudden light(e?)ning, but quickly regained control of the plane"
Every couple of months I try to learn how fourier transforms work and every time I retain about 5% of it. I should have a complete understanding by 2022.
It's easy, you just take an infinite number of sine waves whose amplitude/wavelength/x_offset are determined via [mumble] and then you add them together to get the curve you want.
@Jose Also note that you can edit your posts for up to 2 minutes. Hover over the left side of your post and you'll see a down arrow. Click that and you'll get a menu with "edit" in it.
You can then use the coefficients of those waves to do... Discrete things.
This is very good because some things can only be done discretely, and undescretize(f(discretize(x)) can sometimes be used in place of f(x) where f is a pain in the butt to implement on continuous data
I've actually seen one of those during lab practice in undergrad, it metered frequencies around 50 Hz and it was used to monitor the mains power frequency
Is FFT one of those things that you could theoretically do with a slide rule or three vacuum tubes, and it's only because of Modern Enterprise Design that we need to download a hundred meg library to get it working on the desktop?
The tachometer I linked might be such an example. The metal bars in the device all resonate at a distinct base frequency, and only the ones in resonance with the engine will vibrate.
It's a good exercise to do a DFT on paper, just to get a feel for how it works. There's a worked example on Wikipedia of a simple DFT of 4 points: en.m.wikipedia.org/wiki/Discrete_Fourier_transform#Example Unfortunately, they don't do the inverse transform to recover the original points from the spectrum, but the working is almost identical.
@AndrasDeak Similar to what happens in our ears, except its different sections of the cochlea that resonate, and the "hairs" (attached to nerves) in a resonating section vibrate more than the hairs in a non-resonating section.
with open('brute.txt', 'r') as f: lookup_dic = {word.strip(): None for word in f.readlines()} with open('SaveFile.txt', 'r') as f: lines = (line.strip().split(' = ') for line in f.readlines()) for lookup, val in lines: if lookup in lookup_dic: print(f"{lookup} matched and its value is {val}") lookup_dic[lookup] = val
Here is a quick explanation, I'm making a Python program that "reverse engineer" a Batch game save file and which is "SaveFile.txt", so here is a quick look at the file:
Obligatory disclaimer: dynamically setting a bunch of variables is almost always a bad idea, and you can almost always do nearly the same thing by storing your values in a dictionary. With that out of the way: try updating the dictionary returned by globals() or locals().
The principal danger of dynamic variable names is that you might override a variable name that's already referring to something useful. Suppose your batch game defines a Strength variable, named str. If you update the globals dict with that, suddenly you can't use str() to convert things to strings.
A secondary problem is if you set a name that isn't actually a legal name. Suppose you set the key "class" to be "fighter". You're not going to be able to access that value directly, because class is a reserved word.
>>> globals()["class"] = "fighter"
>>> class
File "<stdin>", line 1
class
^
SyntaxError: invalid syntax
You can still access the value by retrieving it from the globals dict, e.g. print(globals()["class"]), but this defeats the ostensibly most attractive feature of using dynamic variables in the first place: so you can access variables without using dict indexing syntax.
I'd argue that the greater concern over mucking with globals is the difficulty in finding errors. I'd go as far as to say that almost all best practices are geared towards making code maintainable and more long lived.
Even if you're certain that you'll never overwrite built-in functions or keywords, you might end up discovering that dynamic variables don't win you much clarity over using a regular dict. Especially if you need to do anything remotely fancy, like "given a variable whose name is stored in the string s, find its value" or "determine whether a variable whose name is stored in the string s exists at all". Neither of these can be done without using dict methods on the global dict.
if you're implementing a REPL or something you might need to do just that, otherwise it just muck the boundary between "data" and "code" in a confusing way
If sheep1coder's ultimate use-case is "I want to extract these values from the file and dump them into a REPL with known-good names so I can experiment with them in a freeform manner", then that's about as close as you can get to an actually good justification of dynamic vars
Or, hmm, maybe "The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking" does not explicitly mean that iterable unpacking is legal within each of those literals. But it's easy enough to confirm that it's legal in lists and sets by observing the starred_list element in docs.python.org/3/reference/expressions.html#list-displays and docs.python.org/3/reference/expressions.html#set-displays
I'm not sure where "tuple displays" are defined in the syntax, since they don't have their own section like list and sets and dicts do. I think it's a subset of Expression Lists
@piRSquared I've contemplated doing that, but the readability sucks. And I'd rather avoid the overheads of calling reversed on every index, value pair.
@AndrasDeak The disk inside the case is still floppy, though.
I have a name a that is pointing to an iterable iter(range(10)). I use up 3 of them with [next(a) for _ in range(3)]; Now I want to prepend another iterable.
def prepend(this, that):
yield from this
yield from that
[*prepend('abc', a)]
# ['a', 'b', 'c', 3, 4, 5, 6, 7, 8, 9]
yeah, neither do I. For a second I anticipated I'd keep having to prepend. It seemed to me having some weird nested chain(iter10, chain(iter9, chain(iter8, ... ))) was bad. But probably not
Yes but no. like 1) it = iter(stuff) 2) use some it 3) prepend some more stuff 4) use some more stuff 5) prepend some more stuff ... all in a dynamic way such that I couldn't have chain(*list_o_iters) in the first place
Doing that with chain is going to progressively slow down as the pile of chains gets bigger, until eventually you blow your stack space and either RecursionError or segfault. Not sure which.
chain.from_iterable is better than chain(*list_o_iters), since it expands the list lazily, so it won't die if list_o_iters is actually an infinite iterable.
I'd probably manage prepended elements with a list used as a stack. append to the list for a logical prepend, pop to consume prepended elements. Depending on whether it makes sense to materialize stuff (or if stuff is already a list or something), I might throw the contents of stuff on the stack too.
stack = stuff[::-1]
while stack:
item = stack.pop()
...
if whatever:
stack.append(new_thing)
@PaulMcG Building a list by cumulative concatenation of lists in a loop isn't so good. It's pretty much like building a string by concatenation in a loop. Joel Spolsky calls it the Shlemiel the Painter algorithm.
It's not the exact same thing but if you create new lists in a loop you can lose a lot. And prepending to a list will have to move the entire contents each time I think.
@connectyourcharger That's slow because it has to shift all the subsequent items up to make room for the new item at the front. It does that at C speed, but best to avoid if you can, and definitely don't do it in a loop. [a] + lst is ok, since it can copy everything to a new list (assuming you have the RAM to spare for the copied list), but once again, you don't want to do it in a loop.
I don't see any reason to consider [a] + lst more okay than lst.insert(0, a). Either option involves going over all of lst, whether to copy the items or to shift them.
@connectyourcharger: No, NumPy doesn't support efficiently adding new elements to an array at either end (or removing elements, either). I'm pretty sure Andras was joking.
@wim The speed difference isn't huge, but it's noticeable, IIRC. But probably not big enough to worry about changing old stack code to use deque instead of list.