« first day (3384 days earlier)      last day (1789 days later) » 
03:00 - 20:0020:00 - 00:00

03:13
hello hello
 
3 hours later…
05:47
I want advise on this - Say a class doesnt have any instance or class attributes, and has only 1 class method that accepts an argument (string) and makes modifications to it using local variables within the method and returns modified value. Now, if multiple threads access this class method, passing different arguments (string), then am I right to assume that there will be no conflicts since each invocation will be an independant call stack/stack frame?
 
1 hour later…
07:16
@variable why is that a class?
07:41
I am looking at an existing piece of code and trying to get my head around it
user10984358
w.r.t the question linked, say I am using this map(lambda x:x in set('aeiou'),'abcde') the set is created only once or?
@TheNamesAlc on each lambda call, so "or"
A lambda is just a one-expression function, nothing magic
user10984358
ahh, thanks!
08:43
@variable Yes, you are right. A class without state and only a single pure function is practically equivalent to that function. However, reconsider why you don't just use the pure function, without the misleading class wrapped around it.
09:11
Thanks
10:10
@AndrasDeak thought so too. Didn't find one. Ended up adding another answer.
I am using this code to remove all the white space in 41,000 rows consists of millions of characters:

`def replaceWhiteSpace(text):
res = []
for i in text:
res = text.str.split()
res = res.str.join(' ')
return res

df['column2'] = replaceWhiteSpace(df['column2'])`

But the code for a very long time like 45 minutes or something. Do you have any suggestions on faster code? thank you
Are you looking for df['column2'].str.strip() instead?
@JackZakiZakiulFahmiJailani Why do you iterate for i in text? You are working on text directly in the body. You are effectively doing the same thing 41,000 times.
And please see the code formatting guide
10:27
@anky_91 I want to replace multiple whitespace with single whitespace. that's why i built that function instaed of using str.strip()
@MisterMiyagi thanks for the tips on code formatting guide. I'm new here :)
user10984358
10:44
If I do d2[d1.pop(0)]=d1.pop(1) which is executed first? the pop that is on the LHS or the pop on the RHS ? d1 and d2are dicts
RHS is executed first
that's how a, b = b, a works as well
user10984358
thanks, is this some basic understanding I am missing here that RHS always first? even in cases where there is a function call on the LHS and a literal on the RHS
RHS always comes first
@TheNamesAlc please don't
when you have to ask yourself this question it's a good sign that you're doing something horrible
just because you know what happens with arr[++i + inds[j++]++]++ you shouldn't do it
Python doesn't care whether you have literals or calls here or there, it only knows statements and expressions. In an assignment statement, the RHS expression is evaluated first.
user10984358
10:51
noted, thanks! I was just messing with stuff like this for preparing for my interviews :)
in your example I don't think it matters
come to think of it I'm not sure you could even write something ambiguous in that topology
it's hard to write UB-looking things in python
anyone know a dupe for "quotes inside string"?
oh yeah I used that the other day
hammered
11:43
is there a canonical answer to import library with same name as script?
yes, in the canon
attribute error though, there
closed
and deleted
Cabbage
Good thing nobody posted an answer on that before the OP wisely decided to delete...
12:01
Has anyone in here ever successfully ran a tkinter app in a thread?
should be exactly equivalent to running a tkinter app in the main thread, shouldn't it?
@SebastianNielsen I've used threading successfully with Tkinter. But the main GUI process & its event loop should run in the main thread, otherwise flakiness may occur. ;)
Oh, I forget the ".start" after the Thread. That's why it wasn't working
wups
So, yea, it should work and it does work :p
@PM2Ring Huh, really? What's so special about the main thread?
I am going to run my tkinter app in a thread that is not the main thread. Perhaps, I'll discover "the why" he is talking about.
12:18
@Aran-Fey To be honest, I forget the details. But it is a known issue. I'll see if I can find a relevant SO post...
Tkinter guru (& former Tcl coder) Bryan Oakley says here:
Tkinter isn't thread safe, and the general consensus is that Tkinter doesn't work in a non-main thread. If you rewrite your code so that Tkinter runs in the main thread, you can have your workers run in other threads.

The main caveat is that the workers cannot interact with the Tkinter widgets. They will have to write data to a queue, and your main GUI thread will have to poll that queue.
All my threaded Tkinter stuff uses that queue-based strategy.
Wow those are some awful answers to that poor OP's question
Hmmm, I'm not entirely convinced that "main thread" means "your program's original thread" and not "the thread that's running the tkinter mainloop" there
Just a heads up for next visitor or maybe OP 6years later: The main problem besides tkInter and threads is that "threading.Thread(showimage(im))" does not execute "showimage" in a thread, but calls "showimage(im)" and provides the return (None) as argument to the Thread constructor. "Thread(target=partial(showimage, im))" would be correct thread creation wise. — SleepProgger Oct 21 '18 at 7:57
As usual, the real answer is in the comments and years late
As Bryan mentions, you often don't need threading, if you organise your event handling correctly, and use stuff like the .after method. But it is handy if you have back-end processing that can take a long time.
@Aran-Fey Feel free to be sceptical. It can sometimes appear to work, until it doesn't. ;)
Looks like the latest pip version has broken things. I did a python -m pip install --upgrade pip
and then any command (try pip list) fails
Anyone facing similar issue?
12:33
Here's an answer by Martelli affirming that Tkinter is designed to run in the main thread: stackoverflow.com/a/3567284/4014959
opening an image is definitely something that can pause your GUI for a while, I can't blame the OP for wanting to do that in a thread
Hmm, that does sound like they're referring to the "original thread" rather than the "mainloop thread"
@Aran-Fey If opening images takes a long time then you can do it using .after so that the GUI doesn't get paused. (Unless you actually want the user to wait until the image is loaded).
12:49
Wait, what? How does doing it with .after prevent the GUI from freezing? As long as there's only one thread, it can't open the image and run the mainloop at the same time, can it
A couple of years ago I wrote a fancy Tkinter threading demo. It's an image server that lets you display multiple images in separate windows, and the GUI is always responsive, no matter how long it takes to create each image. It works nicely, but when I finished it, I realised U could get almost the same functionality without threads. The threaded version is on my HD, but I put the non-threaded version in a Gist.
@Aran-Fey I think stuff in an .after callback runs in a temporary thread. I forget the details...
Anyway, here's that Gist: gist.github.com/PM2Ring/…
.after is usually used to queue widget updates from other threads, so I'm pretty sure they run in the main(loop) thread
The docs aren't clear: effbot.org/tkinterbook/widget.htm#Tkinter.Widget.after-method "Tkinter only guarantees that the callback will not be called earlier than that; if the system is busy, the actual delay may be much longer".
import threading
import tkinter as tk

win = tk.Tk()

win.after(0, lambda: print(threading.current_thread()))
win.after(1, win.destroy)

print(threading.current_thread())
win.mainloop()
same thread on my machine
user10984358
13:04
Can anyone look into this snippet dpaste.com/2GXHKP6 and tell me which pattern should I follow? my logic after I get temp is like 5 lines
user10984358
Should I go with foo or bar?
> import thread # should use the threading module instead!
So why not do that in a tutorial-like thing? :/
@TheNamesAlc side note: do you really need to pop all the time?
Pretty sure I've seen that exact line of code somewhere on SO. It's probably copy-pasted
@AndrasDeak Yeah, that's rather ugly. I assume it's ancient code. But why bother writing that comment instead of actually fixing the demo code?
user10984358
well I am re-arranging the dict structure I got from parsing an XML using xml.etree.ElementTree , so the values have to be moved to the structure I want
user10984358
13:10
this is just a broken down version where I want to assign temp to some other index
@Aran-Fey Ok. Thanks for testing that.
if str.findall('\w{5,}') suppose to findall string below 5 times occurences, what is the code to look above 5 times occurences?
@PM2Ring exactly
@TheNamesAlc OK, just wanted to make sure you're not using pop when you really just need d[key]
\w{5,} finds sequences of at least 5 word characters. If you want more than 5, use \w{6,}. If you want less than 5, use \w{,4}.
@TheNamesAlc I recommend to use a well-defined type structure. If you want more than one id sometimes, then always use a list. Even if it has just one element.
13:19
@Aran-Fey but I tried this code:
`>>> df['column2'] = df['column2'].str.findall('\w{,4}').str.join(' ')
`
and my result get some words like this:
`spor t` from the word `sport`
I can recommend using type annotation for your code just to avoid doing stupid stuff. If it's hard to annotate, it's probably not a good idea.
user10984358
well I am using stackoverflow.com/a/39539757/10984358 to convert my xml to dict
Incidentally, Fredrik Lundh created Tkinter, PIL, and ElementTree. He's undoubtedly a smart guy, but some of his design decisions are somewhat questionable...
@JackZakiZakiulFahmiJailani Yeah, because spor is a sequence of less than 5 word characters and t is also a sequence of less than 5 word characters. What did you expect to get as output?
@Aran-Fey I want to get all the word which characters are below 5 times. many of the rows contain more than 2 or 3 words
13:24
If you want to match whole words, you need to add word boundaries: \b\w{,4}\b
@Aran-Fey I tried:

`
df['column2'] = df['column2'].str.findall("\b\w{,5}\b").str.join(' ')
`

but I got 0 results
r"\b\w{,5}\b"
always add that r prefix when you write regex
works like a charm now. thanks @Aran-Fey :)
Nasty little backslashes
13:50
Nassssty backslashessesss, gollum
14:15
Hi anyone here willing to give me a wee bit of advice ( pastebin.com/xFyq5C6X ). I have a shed load of if statements in this code and wondering if anyone could point me in the direction of cleaning it up. I have had a look at Switch statement (Java) but Python does not have a function like that
Short answer: dictionaries can often replace switch statements
Cool thanks Kevin. Never even crossed my mind
also, it's easier to maintain 1 container, rather than 20 different lists
Specifically in your case you'd have a dict of lists, where the keys are the team names. And then all_units[team_name].append(int(unit_number[0])) or similar
dictionaries help there as well
and i think i just got Kevin'd
14:18
I was about to say, having lots of different variables with nearly similar conceptual meaning is often an antipattern
(Even if you name all those variables separately you can also put them in a dict for this step of the logic. But I agree that having just the dict of lists is probably better altogether.)
It's possible to reduce the line count of this program without refactoring away the variables into a single all_units dict as Andras suggests, but if you're going for A+ work, you may as well go all the way
Oops beaten
Tis the season
clearly I have work I should be doing
14:20
laurel
Thanks for the input guys
Just a small questions guys I am new in python, I have a loop which produces to variables (var1 and var2) how do I pass both of them to a dictionary, the first as being the key. Thank you!
Perhaps my_dictionary[var1] = var2
@MatthewSwart here is an example of how you'd create the dict without refactoring out the variables. Here is an example with the variables refactored out. In the latter case, you don't have to declare any team names ahead of time -- they're automatically created in the dict as you iterate over your workbook.
(disclaimer: I didn't test either of these, beyond verifying that they don't crash with a SyntaxError)
I use this code to replace certain string to whitespace, but I just realized it was a bad code since it also replace single character in a word:
`
df['column2'] = df['column2'].str.replace('w', ' ')
`

So, for example this two words from a row:
`
yes g eagle
`

become bad like this:
`
yes eale
`
any suggestion?
14:30
r'\bg\b'
Strange, I'd expect str.replace('w', ' ') to replace all instances of the letter "w", not "g"
I'll chalk this one up to "my actual code is somewhat more complex than this, and while I was composing a simpler example, I got things a little mixed up"
@Kevin Thanks again I am trying kind of the same but using lambda I have copied your examples and honestly grateful. One ain't learning unless one brakes and fails
@JackZakiZakiulFahmiJailani sounds like you/your code is doing something else, or some other line of code is causing this particular replacement. Or that you've provided an example but not one that works with your actual code (Does df['column2'].str.replace('w', ' ') actually replace the "g" in "yes g eagle " ? )
14:39
@Kevin haha ... my mistake
@Aran-Fey thanks again mate
@ParitoshSingh it should be str.replace('g', ' ') ... sorry for my mistake
aha. no worries
Twice in the past week I've encountered web pages that clearly have more than one screen's worth of content, but have no scrollbar. Please contribute to my kickstarter to destroy the Internet and replace it with a subset of HTML that has only plain text and <a>.
Not only was the scrollbar absent, but the arrow keys and the page down button had no effect. Not only that, but highlighting text on the page and moving the cursor down did nothing. It seems inconceivable to me that the developers could have done all this accidentally
some dev probably fell for the ol' "I'm just gonna make a small change, no need to test before deploying"
14:54
In the first encounter I was able to restore functionality by googling "css hide scrollbar", finding stackoverflow.com/questions/3296644/…, and deleting the overflow property from the body element. Encounter #2 was beyond my reverse-engineering abilities.
although it also could've been caused by someone fiddling with the CSS for page X and not noticing that the same CSS also affected page Y
It occurs to me now that the pages were possibly trying to do the old "obscure all page content until the user clicks the 'ok, I'll disable my ad blocker' popup" trick, but I couldn't tell because my ad blocker was blocking it.
morning cabbages, all
@Kevin I'd still prefer that to the new-fangled "information you came for can be found somewhere between pages 12 and 17. Click <here> for page 2"
that's when I close the tab
surprisingly many websites actually behave very poorly when you have adblock active, come to think of it
user clicks a button -> nothing happens. clicks again -> works
14:57
I never try clicking twice, but I have noscript which is more brutal
@AndrasDeak I faced that same frustration on site #2, actually. After I found an alternative page with a functioning scroll bar, I discovered that the page had 20 results out of 150, with a "load more" button which loaded another 20 results.
I wanted the very last result, naturally.
I tolerate "load more"s. And prefer them to "page loads automatically when you scroll down ad infinitum"
the problem with noscript is that most (all?) of the websites I use require JS to work :/
you can still allow those specifically and visit random pages without jS
The page in question was rustyquill.com/the-magnus-archives. I notice it currently has a perfectly functional scrollbar, which baffles me, because AFAIK I'm using an identical browser on this computer compared to the one from yesterday
15:02
I have every ad service and facebook domain blocked and almost everything works fine
something breaks post embedding in the Hungarian news site that I read, but I once allowed everything in noscript on the page and it still wouldn't work...
The embedded player has "page loads automatically when you scroll down ad infinitum" behavior, but since I couldn't scroll down far enough to get it to load more yesterday, I had to inspect source and locate the url that the iframe was pointing to, embed.acast.com/themagnusarchives?feed=true. That page has a "load more" button and no scrollbar trickery.
@Kevin that reminds me: how's your laptop pinging problem?
No improvement since my last update. The Lenovo can ping the Dell, but not the other way around.
This is annoying because I want the Lenovo to be the server in the half-baked project I'm toying with. I could make it so that the connection is initially established by the Dell waiting for a connection and the Lenovo making a connection, after which point the Lenovo behaves like a conventional server and the Dell like a conventional client. But it bothers me on a conceptual level.
@Kevin
@Kevin Thanks for the suggestion I got it working with lambda and it cleaned up nicely pastebin.com/ujCCpjkR
And if I extend functionality later that allows multiple simultaneous client connections, it will no longer be feasible to have this inverted connection setup
@MatthewSwart Glad to hear it, but I'm curious why my first code snippet didn't work for you. In theory, you shouldn't need lambdas at all here.
15:12
@MatthewSwart ew
lambda input : eastern_unit.append(input) is practically the same as eastern_unit.append by itself. Just slower and much harder to read.
Rule of thumb: Whenever you have to type the same line of code 14 times, you can probably simplify it
It was a case of ticking a box. This is college work and have to have lambda's in the code he gave us data and we are meant to take the 495 files and input them into one excel file certain points required one was lambda
And if I used your code @Kevin personally I would have felt like I have cheated the assignment if you get me
15:16
Ah, the old "I'm being forced to shoehorn in this technique even though it's completely useless here" quandary. My advice is to grin and bear it, get your A+ for the assignment, and then never do it like that again
If they want to test your lambda skills they should give you an actual task that lends itself to them. Like using a non-trivial key function for sorting, or curve fitting with scipy, something like that
I have hundreds of individual words that I want to remove from a dataframe. Like these individual words in this list:

`ListWords: ['asc', 'img', 'bg'] `

I want to remove all that words from 41,000 rows without having to run code reccurringly like this:

`df['column2'] = df['column2'].str.replace(r"\basc\b", " ")`
`df['column2'] = df['column2'].str.replace(r"\bimg\b", " ")`
`df['column2'] = df['column2'].str.replace(r"\bbg\b", " ")`

I tried this code:
`
df['column2'] = df['column2'].apply(lambda x: ' '.join([word for word in x.split() if word in (ListWords)]))
Seeking assistance online for early-to-mid programming classes is so awkward, because often the answer to your problem is "there is exactly one correct way to do this, which I will now describe in perfect detail" and then you're like "even if I closed the window and replicated the solution from memory, it would probably be character-for-character identical to what this comment suggests"
@JackZakiZakiulFahmiJailani Can you please format your code properly?
I agree with both of you but for now I am biting my tongue taking the quick marks cause I am now completely done with this assignment and running because I really want the time to carry on with my base project. I have an electric scooter I have hacked it so that the bluetooth is now cellular and streaming data to my db.
That data is then been presented on a web application and feed in to a machine learning application so that it can learn my schedule. This will then txt and email my lecturers when I am running late. Basic but fun
15:24
doesn't sound basic to me; good job!
holy geez! that's not basic at all. Just hacking the bluetooth to run over cellular (what the holy what?) is beyond me
It's easy, you just do pip install bluetooth_to_cellular and pip install web_application_db_presenter and pip install schedule_machine_learner and then you glue them all together
I'm getting some sort of error with general consensus control (gcc) when I try to do that :(
@JackZakiZakiulFahmiJailani If your only problem with the "recurring" approach is that you have to write one line of code for each element of ListWords, then you can use a for loop instead:
for word in ListWords:
    df['column2'] = df['column2'].str.replace(r"\b" + word + r"\b", " ")
If you're seeking a solution that does not iterate directly over ListWords because ListWords contains millions and millions of elements, then this probably won't help
df['column2'] = df['column2'].apply(lambda x: ' '.join([word for word in x.split() if word in (ListWords)])) actually might be reasonably efficient in that case, if ListWords is a set
15:38
There is a good few projects online that have done just that with raspberry pi I have used an arduino to read the signals from the old bluetooth wires and then slapped a GSM shield on to that it also runs on a seperate power supply so that it aint chewing the crap out of my on board battery
... Although it seems like you should do if word not in ListWords, since what you've got now would include only things that appear in ListWords and exclude everything else. That sounds like the opposite of what you want
TC guys thanks for the suggestions
Incidentally, I notice that pandas.Series.str.replace accepts either a regular string argument, or a regex argument. Does it assume that a string object is always a regular string, or does it somehow try to smartly inspect the string to see if it looks regexy?
Based on my naive understanding I'd expect df['column2'] = df['column2'].str.replace(r"\basc\b", " ") to replace the literal character sequence "<backslash>basc<backslash>b" rather than treat the "\b" as word boundaries, but I'm prepared to be surprised
@Kevin actually indeed it should be like my initial code, but instead it should be if word not in ListWords
@Kevin thank you for pointing it out
If you do go with a split-and-join based solution, keep in mind that this may mangle your string in ways unrelated to blacklisted words. For example, the string "foo<ten spaces go here>bar" will become "foo bar", with one space, since split gloms together multiple whitespace characters
And newlines/tabs will be converted to spaces, etc etc
15:49
@Kevin I have already replace all punctuations and special characters with another code to white space, do you think that's the problem?
It depends on what you're trying to do. I've seen quite a few natural language parsing projects where the first thing they do is strip out everything except the actual words. It's not a problem if the words are the only thing you're interested in
If your project will eventually contain a step like "ok, now take the sanitized data and restore it to the format that it was originally in", then it's going to be painful to rediscover where all the punctuation and special characters used to be
But not all projects need to do that, so ¯\_(ツ)_/¯
I think it's all working out for me @Kevin,
thanks btw :)
You can just use the usual regex approach of replacing multiple words... eg - your pattern is r'\b(word1|word2|word3)\b` and your replacement string is '' then pass regex=True to Series.str.replace...
if (visited[row][col] == 1 or grid[row][col ]==0):
"list of out rnage"????
A "list out of range" error usually indicates that the index you used for your list is outside of the boundary of the list. If you have a 3x3 grid, then my_grid[23][42] will fail.
Notably, my_grid[3][3] will also fail. Remember that lists are zero-indexed
15:56
cabbage
It's hard to give more specific advice without an MCVE. The linked dpaste is not an MCVE because when I run it, nothing happens.
@Kevin it initialise wells
well**
I notice that function1 calls function1(row+1, col, grid, visited). Suppose that the grid is 3x3 and the current value of row is 2. When this recursive function executes, it will pass row+1, which is 3. But as we established, my_grid[3][whatever] will crash.
Or, hmm, that's a bad idea because negative indexes are valid, so not all out-of-bounds problems will trigger an IndexError
Better to do a LBYL-style approach with something along the lines of if not (0 <= col < width and 0 <= row < height): return 0
Just posted in The h Bar:
Hmm, riffing off of the "super buff dudes answer philosophy questions" meme, while simultaneously poking fun at Stack Overflow's tendency to answer questions by not answering them, while simultaneously using visual metaphor to illustrate why advice that's useful for large cats/devs is not so useful for housecats/neophytes. There are many layers here.
16:08
Hey, that's exactly how my cats solved the problem! looks for the dupe button
Hot take: "any advice please?" should be a free pass for commenters to give you any advice, including "stop trying to do the thing you're trying to do". If you want to know exactly and only how to do X, then ask "How do I do X?"
Sadly we don't live in such a perfect world, and commenters will tell you not to do X even if you ask exactly and only how to do X. But wouldn't it be nice?
this picture on an onion tier level
@Kevin But if we suspect that it's an XY problem, and that you ought to be asking about X, but you're asking about Y instead, then we should try to clarify that before answering.
oh man, how many inception levels are we going down ?
16:20
moral of inception: if you run a VM inside a VM inside a VM, everything becomes really really slow
I give myself a free pass to give whatever advice I desire, by prepending it with "this isn't directly related to your problem, but:".
Ok, I'm done
Note that the leopard's laptop computer is running on battery power, but the lion is using a manes powered desktop machine.
if you had a matrix of 0s and 1s, and each turn if an element which is 0 if adjacent to 1 (up,down, left, right)
turns to 1, how long til the matrix turns all 1?
how would you approach this?
For each pixel with a zero value, determine the manhattan distance between it and the closest pixel with a one value. The largest of these distances is equivalent to the number of turns required to turn all pixels into ones.
@Permian That sounds like a breadth-first search.
16:26
Empirical approach: write a cellular automaton obeying the rules you have described, and run it until everything is a one.
It'll be O(turns*rows*columns) but maybe that's good enough?
@Kevin what about bfs from each 1 cell?
Yeah. It's like an inefficient flood fill algorithm.
It should be sufficient to calculate the distance between all the 1s and all the corners.
I'm not totally sure what the complexity of the "maximum-of-minimum distances" approach would be. O(rows^2 * cols^2) if you don't put any effort into caching the positions of cells that are likely to frequently be the closest pixel to many zero pixels, I suppose.
@MisterMiyagi But what if all the corners are ones?
Right, just the 1s
Basically, you only need to look at the points exactly between two 1s. All others cannot be the furthest away from a 1.
16:30
Maybe I misunderstand the requirements. Suppose the input is a 100x100 grid which is all zeroes, except for one pixel in each corner. If I understand correctly, it should take 100 turns* for the grid to become completely one-filled.
(*give or take a turn, I can't be bothered to work out the fencepost math)
Hmm, I think I've misunderstood what you meant by "all the corners". I thought you meant the four corners of the grid, but maybe you mean the points of intersection of the Voronoi diagram that uses each 1 pixel as the seed for a cell.
In which case I agree that you only need to inspect the points exactly between two ones, AKA the edges where two voronoi cells meet
Tar basic idea is a Voronoi diagram, but you must account for the corners of the grid as well.
e.g. if you only have one 1 in a corner, you still have to account for the time to reach the other corners.
I'm uncertain about whether you need to inspect every pixel along the edges, or just every pixel at the intersection of 3+ cells. I'm 75% leaning towards "you must examine the whole edge"
And yes, you probably need to have special treatment for the corners and/or edges of the grid too
Wow... looks like the CEO has introduced themselves on MSO...
5
unless there's a cool way of faking a staff badge...
In any case. Calculating voronoi diagrams is somewhat expensive -- O(N log N) where N is the number of one-valued pixels. So if the input has a lot of ones, you're probably not getting a huge performance boost compared to a simple BFS
whats wrong with this
queue1 = deque([])
16:41
@Kevin If all 4 corners are 1 we can grow from all corners simultaneously. I was going to say that should take 49 turns, but that doesn't quite work because we're on the Manhattan metric, and can't grow diagonally.
Certainly N log N is usually better than N^2, but if you account for developer time too, then en.wikipedia.org/wiki/Fortune%27s_algorithm looks like a bit of a headache to implement
@Permian Looks syntactically valid to me. I find variable names ending with a number to be distasteful, but it won't cause an error or anything.
i had to import collections
Yes, that is where deque conventionally lives
do you understand the times bit in the python solution?
2nd python solution
As in, "why is it doing return max(0,times-1)?"? I guess he's trying to account for the possibility that the grid is already filled with ones before any turns elapse
16:48
@Kevin no how does the counter work?
There are probably more elegant ways to do that
With 1's at the corners, my brute force N² solution for nxn grid comes up with n-2 turns.
like i dont want to count every 0 that goes into the queue
To be clear, are we talking about the submission starting with "Here is a solution in python with bfs if anybody is looking for a clear and easy to understand solution"? I don't see a Counter object in that solution.
the times
acts as a counter
so it increases every iteration in the for loop
16:49
Ah, so by "counter" you don't mean "the Counter class, as found in the collections module" but rather "an integer that gets incremented every time an event occurs". Got it.
 for i in range(rows):
        for j in range(columns):
            if grid[i][j]==1:
                Q.append((i,j))

    while(Q):
        for _ in range(len(Q)):
            x,y=Q.popleft()
            for dir in directions:
                i=x+dir[0]
                j=y+dir[1]
                if 0<=i<rows and 0<=j<columns and grid[i][j]==0:
                    grid[i][j]=1
                    Q.append((i,j))
        times+=1
    return max(0,times-1)
when the times variable update?
times increments at the end of each iteration of the while(Q): loop. Each iteration of that loop is equivalent to one "turn" of the simulation.
It doesn't increment every time it sees a 0 pixel, or anything
what the heck is that indentation
16:51
but surely len(Q) would be the number of 0s
@Permian there isn't really a point to feeding an empty list to a deque. deque() has the same result.
oh, the first line isn't indented correctly, I get it
like how does the times variable work?
it's like using list(list(list())) instead of list().
Hmm, maybe I didn't read the code thoroughly enough. Please hold...
16:55
for _ in range(len(Q)): x,y=Q.popleft() empties the queue and Q.append((i,j)) fills it back up. times counts how many times that happens. It's certainly written in a very confusing way
len(Q) is not equal to the number of zeroes in the entire grid. It's equal to the number of zeroes that are directly adjacent to a one at the current point in time. This number changes as the flood fill converts zeroes to ones.
how does it change though
If by "it" you mean len(Q), it changes in two ways. It gets smaller with each popleft call, and it gets bigger with each append call.
i know that
but how does that combination mean that i can find the minimum number of iterations to fill the matrix?
This solution is a bit tricky to visualize conceptually because Q can represent a mixture of data. For example, during certain iterations, it holds 23% of the state of the current turn, and 77% of the state of the next turn.
A more conventional BFS approach might use two separate queues for the current turn state and the next turn state. This is slightly less memory-efficient, but easier to understand conceptually
17:01
yes but nobody has done that
FFurus, the commenter with the first Python solution, has done that. He uses q as the current turn's state, and new as the next turn's state.
(aside: a variable with the name new gives me shivers, since that's a reserved keyword in 90% of the languages I've used)
Even the two-queue design is not trivially easy to understand, if you've never encountered it before. So don't get discouraged if you're feeling fuzzy about the whole thing.
step 1) they populate a queue with all the zero coordinates
q = [[i,j] for i in range(rows) for j in range(columns) if grid[i][j]==1] populates a queue of all the one coordinates.
i think its the while () then for() bit that is confusing me
@Kevin true
I was going to suggest getting familiar with the contents of en.wikipedia.org/wiki/Breadth-first_search but I notice the pseudocode doesn't give you a simple way of identifying the "current turn" so maybe that's not so helpful.
17:10
@Kevin i get that though
but everytime we enqueue at the end
how queue is never not empty
I bet there's a nice gentle introduction to the two-queue design somewhere out there on the Internet, but heck if I know where it is
i understand it now
i think
@Permian The enqueue command is inside the conditional if w is not labeled as discovered then. Eventually, every node will be marked as discovered, and that conditional will always fail. At that point, the queue gradually shrinks down to zero elements
i still cant see why we do times-1
the -1 bit
ugurthesolver's approach simulates one more turn than it really "needs" to. His queue is a collection of one-valued pixels that might have a zero neighbor. But not all of them do. On the turn the grid is completely filled, he still appends the freshly-converted pixels to the queue, even though there can't possibly be any zero neighbors on the grid. It's only in the next iteration of the while that the queue finally empties out.
Since he simulates one more turn than necessary, he has to subtract one from the turn count to get the right answer.
FFurus' solution also effectively simulates one more turn than necessary, but his if not q: break ensures that time is not incremented in the final iteration
17:21
ugh
@Aran-Fey A curate's egg, so to speak.
@MisterMiyagi All good things. Pre-commit, poetry and tox ftw!
@Kevin do you know what the time complexity would be?
O(number of zero-valued pixels in the grid)
Or, hmm, I'm not counting queue initialization, which iterates over the entire grid... So just O(number of pixels in the grid)
BFS is O(V+E)
so i didnt know
@Aran-Fey s/too stupid/not quite smart enough/
17:27
For the kind of lattice we're working with, E ~= V*2, so that checks out
More specifically, V = R*C and E = 2*R*C - R - C
Hey @holdenweb, do you feel like working for SO? They're looking for a new product manager. stackoverflow.com/company/work-here/1988644/product-manager-qa Megan Risdal's gone back to the Kaggle team.
in Tavern on the Meta on Meta Stack Exchange Chat, 2 hours ago, by Yaakov Ellis
If you want to work with me and are an awesome PM, please apply for that position.
@PM2Ring harsh
@PM2Ring what's Steve done to you to warrant suggesting that? :p
"Work at SO" sounds like "live in interesting times"...
17:51
want to lose your job at a moment's notice for having sensible opinions? then we've got a spot for you!
@JonClements Fair call. ;) But I figured it was worth mentioning, just in case.
18:07
Not looking, thanks, but your concern for my bank account is appreciated. Not sure I'd want to hitch my star to SO's wagon just now. 'Specially since I work at Labster.
Besides which, am I "an awesome PM"? That sounds to me a bit like awesome BS ...
things often are what they seem
18:30
I want to know the sum of all keywords from a column. Currently with this code it gives me the count of each row, not all rows:
`list(map(lambda x : len(x.split()), df['column2']))`

Any tips?
@JackZakiZakiulFahmiJailani please see our code formatting guide to chat and practice in the sandbox if necessary
4
If that expression gives you a list of integers, do sum(your code goes here) to add them up
it works @Kevin thankss
Or just replace list with sum
>>> df
                              a
0                        potato
1                      po ta to
2  fish and chips and fries too
>>> len(df['a'].str.split().sum())
10
oddly enough list-of-strings-valued pandas series can be summed to give you a single large list
not very memory-efficient, though, I think we can do better
18:34
I thought that should add up to 11, then I realized 'a' was the column name, not a 1-word value
My crystal ball suggests that in ten minutes we may discover that the requirements are actually "find the total number of unique keywords in the series"
I guess using sum(map(len, ...)) on it would be best
@AndrasDeak I tried to use ` like this ` but i don't know what's wrong
look at the guide, it shows how to do it.
As indicated within sopython.com/wiki/…, backticks do not work in multiline messages
wim
wim
18:43
why don't backticks work in multiline messages?
nothing works in multiline messages, except URLs sometimes...unless it's all code or quote
got it now:
>>> list = []
👍
haha, i had a "uh, what" moment till i realised that probably isnt real code :)
hahaha
tips to duplicate line in spyder IDE:
>>> ctrl + alt + up_arrow
18:54
A recent question has a variable for every letter from a to z, and then from a1 to a52. I admire their determination
I would get to around g before saying "this is exhausting"
I hope their next question is about eval
The program is supposed to execute one of about twenty formulas relating to e.g. the area of a cone, etc. The most concise version of this probably does use eval.
oh wow, that numpy guide looks pretty nice. those visualizations are awesome
it was someone's Google summer of Docs or something project
03:00 - 20:0020:00 - 00:00

« first day (3384 days earlier)      last day (1789 days later) »