« first day (3093 days earlier)      last day (1870 days later) » 
03:00 - 19:0019:00 - 23:00

3:00 AM
cbg
Look at this, it is crazy:
the question i mean
19
Q: Python: return float 1.0 as int 1 but float 1.5 as float 1.5

Raymond ShenIn Python is there a way to turn 1.0 into a integer 1 while the same function ignores 1.5 and leaves it as a float? Right now, int() will turn 1.0 into 1 but it will also round 1.5 down to 1, which is not what I want.

With my answer, not that rated, just got two extra up-votes from some edits i made
6
A: Python: return float 1.0 as int 1 but float 1.5 as float 1.5

U9-ForwardUse the following function, is_integer is a function from the float class, You can just use this method to_int, that which uses is_integer to check whether it is a integer-like float (i.e 1.0) or a actual float (i.e 1.5), If it is a integer-like float, return int(a), otherwise just return it's ...

 
Don't one box links please
pro-tip: if you must paste a link (which, in this case, we rather you didn't if you are only posting it to brag about upvotes), then add some text to it so it isn't one-boxed
 
3:15 AM
Oh man...
 
3:48 AM
I am little too gooffy now:
>>> s = 'I am python'
>>> for x, y in zip(['p', 'y', 'y', 'z', 't', 'x'], ['y', 'p', 'z', 'y', 'x', 't']):
	s = s.replace(x, y, 1)


>>> s
'I am python'
>>>
> goofy
 
cabbage
 
cbg
 
4:23 AM
Let's say I have a list with tuples:

items = [("a", "b"), ("c", "d")]

What code can I use to transform the list to the following:

items = [["a", "b"], ["c", "d"]]
 
4:45 AM
@RichieBendall items = [list(tup) for tup in items]
 
Thanks!
How do I get the last item in a list that matches a regex?
 
@RichieBendall [x for x in y if re.match(r'regex', x)][-1]
 
Thanks!
 
or re.search() if that's what you mean, the difference is subtle (match anchors at the beginning implicitly)
 
 
2 hours later…
6:35 AM
... eight more points to go before gold badge - this is excruciating
 
@tripleee it'll happen :)
 
@tripleee Wow, i know how it feels... i got this a month ago... and got it finally
cbg
 
I was hoping to get it in March but then I fell ill ... and still tried to answer Python questions while in bed with the flu, but not getting a lot of, ahem, positive feedback
 
Wow, unlucky
I at least could get it at February
 
7:13 AM
It's always a little frustrating when you have way more in score than you need to get a badge but not enough posts to meet the criteria
(although I find that it happens more on meta than main...)
 
Of course, wow! you almost can get python 3.x gold-badge
 
Did something change in python's import system between 3.5 and 3.6? For some reason my package can't be imported in 3.5...
 
Answer five more questions, than you'll get it
 
Never mind, it can be imported... but for some reason pytest can't import it
 
@U9-Forward oh wow... you're right... hadn't noticed that...
 
7:17 AM
@JonClements You're very close
:-)
 
it'll happen eventually :)
 
Always like that, lol :-)
 
(my answering rate is massively down these days - but all things in time etc...)
 
Same with tripleee
 
everything's eventual
 
7:20 AM
Yeah
Wow, some point you had 2 months without an answer
10 more up-votes to go for my bronze
I have enough answers...
 
So apparently typing.Type didn't exist back in python 3.5.0 even though it's documented...
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from typing import Type
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'Type'
¯\_(ツ)_/¯
 
Strange, works for 3.6.0
And 3.6.1
 
class re:
    """Wrapper namespace for re type aliases."""

    __all__ = ['Pattern', 'Match']
    Pattern = Pattern
    Match = Match

re.__name__ = __name__ + '.re'
sys.modules[re.__name__] = re
My number of WTFs/minute is over 9000
 
Wow, lol
 
@Aran-Fey isn't that another shadowing thing?
If not then worth looking at the blame of github.com/python/cpython/blob/3.5/Lib/typing.py
 
7:36 AM
Shadowing? What's shadowing what?
 
@U9-Forward wow... didn't realise that - thought I'd at least done a couple of answers a month or something
 
@JonClements Well, i know, you're busy, as a mod
 
@Aran-Fey locsl typing.py a built-in
 
Ah, no
>>> print(typing.__file__)
C:\Python35-32\lib\typing.py
checks out
 
@Aran-Fey It is a totally different path for me...
 
7:41 AM
:I
 
@U9-Forward not always... there's real life and stuff and other mods are far busier than I am doing mod stuff these days... just massively surprised I didn't answer anything for two months...
 
Lol, yeah
I have a question, why in the top right corner of this page where the tags are say , and not:
 
Networkx release candidate with no python2 is out networkx.github.io/documentation/latest/release/…
 
@U9-Forward thinking about it - I probably have answered each month - but I'm trying to answer in pandas and perhaps I've posted an answer - thought better about it - then deleted it kind of thing
@Andras sweet - haven't used nx in ages :)
 
@JonClements Yeah, i am looking for my pandas silver too, pandas is a good library
rbrb
Using the language you created
Rhubarb
 
7:50 AM
I deny all knowledge of such a thing
wasn't me - can't prove it was me... /me sticks paws in ears... la la la, la la la
:p
 
Cbg
 
 
1 hour later…
9:27 AM
When looping over a dataframe column like:
for item in df['somecolumn']:

How does one assign a new value to that item and have it actually change the dataframe in that position
 
df['somecolumn'][item] = ... probably
maybe dataframes support 2-index subscription as well
 
I'll give that a quick shot
 
oh, don't do that, that'll cause chained indexing
use loc or iloc to set values
Unless I'm misunderstanding something
 
Could be, ive not worked with dataframes a lot. df.loc[item] = ... then?
 
pandas.pydata.org/pandas-docs/stable/reference/api/… ... the syntax is .loc[index(es), column(s)]
 
9:46 AM
@coldspeed probably not
@coldspeed that's what I was missing
 
10:11 AM
 
@Arne pure evil ... we should counter that with "93% of line noise is indistinguishable from nested list comprehensions"
(a former Perl fanboi getting vaguely defensive)
 
=D
I also had a good time writing perl
but reading it was in my experience even worse than the memes make it out to be
 
closed
 
10:35 AM
This question morphed from the original asking about multidimensional dicts, so that part should be deleted, or at least reduced to a footnote and the actual question posted at the start. Anyway sorting (flat) dicts is a duplicate and should be closed as dupe. Anyone got the stamina to sort it out?
 
10:46 AM
unclear/garbled and non-generalizable reasking about the boilerplate code
 
11:12 AM
@coldspeed oh hey... how familiar are you with DateOffset? :p
I ask because I'd like to (even just for myself) resolve what I was trying to attempt in stackoverflow.com/questions/55477201/…
I'm sure it's close but I'm just missing a little bit somewhere and it's bugging me that I can't quite identify what that "little bit" is.
 
11:29 AM
@Arne Man this is so hilarious :D
 
The whole conference is a riot sigbovik.org/2019/proceedings.pdf
6
 
12:19 PM
@wim I'm very late in replying, but generally I don't mind if my answers get edited. Except perhaps for my very highest voted ones, which I am irrationally possessive towards.
If it's above +20, maybe it doesn't need editing :-P
 
Hi community,
How to parse this json string:
{u'display_name': u'University Cheikh Anta Diop, Dakar, Senegal', u'importance': 0.1625, u'place_id': u'332586523679', u'lon': u'-17.46331', u'boundingbox': [u'6.147631', u'16.438497', u'-61.477143', u'1.256522'], u'licence': u'https://locationiq.com/attribution', u'lat': u'14.68731'}
i have the following error: TypeError: string indices must be integers
 
That does not appear to be a JSON string. JSON string literals cannot start with a "u".
 
cbg \o and darn Kevin you fast, as always
 
It looks more like a Python literal. Perhaps instead you could use ast.literal_eval.
>>> s = """{u'display_name': u'University Cheikh Anta Diop, Dakar, Senegal', u'importance': 0.1625, u'place_id': u'332586523679', u'lon': u'-17.46331', u'boundingbox': [u'6.147631', u'16.438497', u'-61.477143', u'1.256522'], u'licence': u'locationiq.com/attribution', u'lat': u'14.68731'}"""
>>> import ast
>>> x = ast.literal_eval(s)
>>> x
{'display_name': 'University Cheikh Anta Diop, Dakar, Senegal', 'importance': 0.1625, 'place_id': '332586523679', 'lon': '-17.46331', 'boundingbox': ['6.147631', '16.438497', '-61.477143', '1.256522'], 'licence': 'locationiq.com/attribution', 'lat': '14.68
 
i receive that from request to a server
thank you, i will try this soon
 
12:37 PM
If the documentation for this protocol says you should accept JSON, and your client is sending you something other than JSON, I think rather than try to parse their data anyway you should tell them "I accept JSON and only JSON, as indicated by the documentation. Please send me only JSON."
If there is no documentation for this protocol, you should write some.
 
Ahh the good ol where's the requirements vs let's draft up the requirements and send it out after the fact :D
 
Then they'll say "WhERe iS tHE doCuMentATioN"
 
12:52 PM
Hmm, the problem with my policy of upvoting a question just for having an MCVE and complete sentences is: once I determine that the question is actually interesting, I can't upvote it a second time.
 
my favourite is business ask for something, we draft a doc, build it out, few months later, we want this to behave this way, but the program does the exact opposite, gets blame for building it wrong, shows doc, well business didn't mean it that way...
 
Mildly depressing that this problem only occurs like once a week
 
Sam
Anyone familiar with Selenium know how to obtain an element by checking whether a certain attribute is contained within the style of a <div> element. I can grab the whole element using xpath using all of the elements style: find_element_by_xpath("//div[@id='pleasewaitbackground' and @style='height: 23689px; width: 1638px; visibility: visible;']") But I would like to find the element by only checking the ID and visibility
 
Aren't you guys also sometimes amazed at how many programmers and how much IT work there is? It feels like there is way more need for IT than I can ever even image :P
 
I try not to think about the programmers outside of this room
 
1:21 PM
^ I enjoy my bubble, it's a nice bubble, sometimes my bubble pop and I'm exposed to the vast ocean, and when that happens I get lost, which leads me to explore new things.
 
I'm registered for PyTexas, first programming related conference. Should be a blast!
 
@Arne I am undecided if I believe actual people wrote that stuff or some neural network trained on lot's of journals. It seems too good for a neural net, yet too stupid and long that somebody would invest so much time in it :D But I tend to believe the second one. Do you know if actual humans wrote this?
 
1:42 PM
I'm 99.99% sure it was humans.
State of the art machine learning still can't write three pages of prose without making mistakes that a human would never make
 
Hi everyone
 
@Mez13 Cabbage!
 
Has anyone ever used the library vecstack? It's used to stack ML models
@Dodge Thar's a warm welcome...what is happening to you?
 
Nothing, just me. Positive and upbeat 95 percent of the time
 
Hmm I like the revealed ambiguity of the English language there. "What's happening?" May be interpreted as a friendly (albeit slightly dated) greeting, while "what is happening?" Can only be read as a sincere query about ongoing events, possibly with a connotation of panic. Or at least that's how I read it.
"What is happening to you?" Is best asked to a mad scientist who is transforming into an insectile monster in front of your very eyes
 
1:54 PM
I realized after the fact the the question was probably "Hey what's happening?"
 
@Kevin It's rather due to the lack of vocabulary in this language...Anyway, we're here for Python
 
But even "Hey what's happening?" without a tone of voice to infer context from can be misinterpreted as a panic stricken cry
 
English is such a mess
 
2:08 PM
Hi guys I have an input like this :
0 0 0 0 0
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
How do I get the index of where 1 is in the simplest way possible?
I don't want to use where function of numpy module
 
next((i,j) for j, row in enumerate(matrix) for i, item in enumerate(row) if item == 1)
 
2:36 PM
s = """
0 0 0 0 0
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0"""
one_loc = s.index("1")
row = s[:one_loc].count('\n') - 1
col = (len(s[s[:one_loc].rfind('\n'):one_loc]) + 1) // 2 - 1
print(row, col)
Too easy
 
>>> list(map(int,divmod((s.index("1")-1)/2, 5)))
[1, 4]
 
How could I forget my old friend divmod? But then, you cheated by knowing a priori to divmod by 5
 
Yep
I thought about deriving column count by searching for "\n" but it displeased me
 
Hi guys I'd really appreciate some help, quick question about pandas.read_csv()

Is there a way to give the index property to each row read by csv? Right now pandas is giving to _all_ the rows the same index, which is the first field it reads from the file.
Do I need to open a question on SO? I didn't find anything online
 
>>> next((i,j) for j, row in enumerate(eval((s.replace("\n", "],[").lstrip("],")+"]").replace(" ", ", "))) for i, item in enumerate(row) if item == 1)
(4, 1)
Hmm, can't say I know anything about pandas' csv reading behavior.
 
2:47 PM
Thanks @ Kevin, @PaulMcG
 
No problem. Anything other than my first suggestion was a joke, if that wasn't clear
 
thank you very much @kevin
I'll open a question on the site then :)
 
Sending good vibes :>
 
3:14 PM
Hi, I'm trying to find number of substrings of string S which contains a given character C in it. I am new to programming ideas, I have written this code, which seem to be very inefficient. Here is the code:

def get_all_substrings(input_string):
  length = len(input_string)
  return [input_string[i:j + 1] for i in range(length) for j in range(i,length)]

string,s=input().split()
sub=get_all_substrings(string)
print(sub)
summ=0
for k in sub:
    if(k.find(s)!=-1):
        summ+=1
print(summ)
 
@Dodge :)
 
morning cabbage
 
Can anyone help me to think about any better idea?
 
Many problems that require you to find the total number of something, can be performed much more efficiently than "iterate over all the things, and add one each time you find a good one"
 
@toonarmycaptain I'm assuming you saw the post about PyTexas?
 
3:16 PM
@Dodge Indeed.
 
As a contrived example, if the challenge was "find the total number of substrings in the string 'XXXXXXO' that contain the letter 'O'", then you can determine that the answer is 7 without ever slicing the string at all
You can simply reason that the only time a substring will have the letter O is when it includes the final character, and that there are only len(the_string) substrings that include the final character
Of course, the math gets harder if the challenge becomes "find the total number of substrings in the string 'XXXOXXX' that contain the letter 'O'". And harder still if you don't have any information ahead of time about the frequency and position of the letter O in the string. But you can still probably come up with something faster than O(N^2) slicing
One approach I might experiment with is: determine the number of substrings of S that don't contain a character C. Then subtract that from the number of possible substrings of S to find the solution.
I think you can do this in O(N) time, even.
 
@toonarmycaptain Should be fun, one of my lab mates may tag along.
 
consider the string "abcOdefgOhi". We can fairly quickly count all of the substrings that don't contain O: "abc", and all substrings of "abc"; "defg", and all substrings of "defg"; "hi", and all substrings of "hi".
Each of these can be efficiently calculated because we know that a string of length n has n*(n+1)/2 substrings (assuming a string counts as its own substring)
So there are 6 substrings of "abc", 10 substrings of "defg", and 3 substrings of "hi", for a total of 19. There are 66 substrings of "abcOdefgOhi", so there must be 66-19=47 substrings of "abcOdefgOhi" that contain at least one O.
 
3:31 PM
@Kevin Wow!
 
nvm...
 
the math base tricks of counting, but the annoying part is when you have to generate the list of substrings :\ then u have to slicey slicey
@Code-Apprentice cbg btw :D
 
3:58 PM
@MooingRawr cbg
 
If I were in Texas, I'd definitely want to check out the Ally Venable Band. Even though Ally is only 20, she's a very impressive guitarist, and a fine singer & songwriter.
 
@PM2Ring and if you aren't in Texas? Then what?
 
cbg all
 
@Kevin Thanks :) I have implemented it and it's faster
 
One of the best guitarists I ever met was a roommate when I was 19-20. He was freaking amazing.
 
4:13 PM
@Code-Apprentice I have to make do with YouTube. ;) The band is currently on tour. They have a few local gigs, then they head over to Europe. They're signed to the German Ruf label.
 
@PM2Ring I remember you mentioning her before. Not too shabby
 
@Dodge She keeps getting better.
 
@Code-Apprentice Can you tell me how you have added your ProjectEuler account status in your profile?
 
I thought If I reply to a message directly the message is supposed to be displayed and my comment appears below, I must have messed something up, hmm
 
@taritgoswami there is some HTML on the projecteuler site somewhere...
 
4:16 PM
@Code-Apprentice Ok thanks, I will check it
 
@PM2Ring Wow, she gets around allyvenableband.com/tour.html (not to Austin though)
 
@taritgoswami oh...nvm...it's just a markdown link to https://projecteuler.net/profile/<username>
 
Anyone using IPython shell? What are the killer features of IPython, in your opinion?
 
The hidden curare needle that pops out of your keyboard when you press ^-Alt-007
 
@Code-Apprentice I can believe it. Plenty of excellent musicians never try to go commercial. Some of the best music I've ever heard was played by unknown musicians jamming in someone's loungeroom.
 
4:20 PM
I've started using it when I'm conducting training, and I'm really liking it over the Python shell on a Windows command prompt. I've been quite happy with regular Python shell in Linux for a long time, but on Windows it's nearly intolerable. IPython fixes a lot of problems with that...
 
@AaronHall %timeit is probably one of the most widely used IPython magics
 
I'd like to see more developers using it where I work, and I want to tell them more about it.... and @Dodge that's a good one that I never use, so I'll try it and add it to my list...
 
cbg! Why doesn't the third line `curr.next = prev` overwrite the value of `next_element` here? I wrote this code and don't understand why it works laurel.

     while curr.next:
         next_element = curr.next
         curr.next = prev
         prev = curr
         curr = next_element
 
@Dodge excellent, added!
 
ahh! because id(curr.next) becomes id(prev) but id(next_element) is what id(curr.next) was before reassignment
cool
 
4:26 PM
@isquared-KeepitReal Have my most reposted link on the matter: nedbatchelder.com/text/names.html
 
@Arne that paint splatter article, tho
 
Wis
g|uys|als why is my answer deserving of the -1? stackoverflow.com/a/55413882/4178053 I think it's the most complete one.
 
finally someone asking the important questions, right?
 
@isquared-KeepitReal Python's tuple assignment is handy for stuff like that. Eg,
prev, curr = curr, curr.next
 
4:32 PM
@PM2Ring yup. aware of that. It definitely looks better. thanks for pointing out
qq. What does it mind to find a loop in a linked list? I am solving a bunch of standard interview questions. And that is one of them. I don't quite get it though
 
@Wis Nothing obviously wrong at a glance. I do wish downvoters would leave comments more often.
 
Wis
i'm genuinely asking so I can fix it
 
because it doesn't explain why it's any of the things you say it is, or how it works, it's just a code dump
 
*not mind, but mean
 
^^See, this is some actionable advice that the downvoter ought to have left in a comment.
 
4:36 PM
ah. I understand. If there is recursion
 
@WayneWerner I read a few of the other sigbovik articles, but I had to stop because it was just getting too silly. And when I tried to read SE Physics questions afterwards my brain was still in spoof mode, and it was impossible to take them seriously. :D
 
Wis
oh okay, I admit saying it's elegant was arrogant, I should edit it out, but it's pythonic because it uses iterables and it's cross-platform because it uses the psutil library which is cross-platform and takes into account both backward/forward slash path separators
 
@Wis Yes, a few explanatory comments would go a long way
 
@isquared-KeepitReal With a linked list, you can't just index into it to get to an item, you have to traverse it. That's generally not an issue if the list is short-ish, & you're using a compiled language. But in Python it's a bit slow. And if the list is long, you probably could use a better structure, eg some kind of balanced tree.
 
@PM2Ring I don't think he's asking whether to use one, its how to find if the list terminates nicely or loops back on itself. This is a question right out of the "get ready for your Amazon coding interview" book.
The solution is to use 2 iterators - have one step one node at a time, the other step 2 nodes at a time. You are done when a) the 1-at-a-time iter reaches the end, indicating no loop, or b) when the two iterators are the same, indicating a loop - I'm pretty sure this is in the solutions section of that book, which is probably where I got it from.
 
 
@PaulMcG Ah, right.
@Kevin Right. Last time I used that I was searching for cryptographic hash collisions, either with MD5 or SHA1, I can't remember offhand.
 
I thought that this would work too: create a dict<node's reference in memory, how many nodes point to this ref>. If at any step we have that there is a key in this map for the node, we know that there is a loop. So we break this next and done. No? This is from the observation that if there is a loop, then there must be two incoming "arrows" into that node
 
I was going to accuse it of being the kind of algorithm you only hear about when you're reading reddit threads about programming interview problems, but I know better than to make such an accusation before an audience with such a broad range of experience
You definitely do read about it in reddit threads, but maybe you also read about it when you're legitimately working with linked lists on an actual real problem
 
I don't. I am prepping for an interview lol
 
@isquared-KeepitReal Yeah, that would work. But it would use linear memory. tortoise and hare uses constant memory.
 
4:52 PM
@Kevin let me check that algo. thx
 
But note that not all loops have two incoming arrows. Consider the case where a.next == b, and b.next == a. Both b and a have only one incoming value, but it's still a loop.
c.next == c is also a loop, but I feel it is not as clear of an example
 
hmm
maybe store the ref of the prev node. In addition to doing what I described. But it doesn't feel like the best way to do it. Need to check the tortoise and hare
 
You might conceptualize it as there being three kinds of linked lists, which resemble "|", "O", and "9" when graphed
"|" lists have no loops. "O" lists have a loop where the last unique node points to the root node. "9" lists have a loop where the last unique node points to somewhere in the middle of the list.
 
Of course, you can have a case where it points to the root node. hmm
 
4:57 PM
My solution would only work for 9
 
If I understand your intention properly, I predict that your approach would work on both "O" and "9" types. But it might take a couple more iterations.
 
It would work on "O" only if we initialized by putting it into that dict. And now I feel like I should not be using the dict to help me in solving this. But my original intention was:

create a dict<ref of the node in memory, number of other nodes pointing to it>
while there is next node:
insert ref into dict with a 1 as value if no ref
if there is ref -> there is a loop, break the link to this node.

However the above would not work for the O. But it would work if we made a small amendment. Namely put the ref of the root node into that dict before we start looping. But, what is the complex
Oh, it's O(1)
But it feels dirty using a dict
 
Incidentally if you're never going to actually check the value of the dict's key-value pairs, you may as well use a set instead
 
true
actually, wouldn't checking if something is in a set be O(n) ?
 
Nah, it's as fast as a dict.
That's pretty much 90% of the selling point of sets
 
5:04 PM
How come? Where can I check this?
But checking if something is in a list has to be O(n)
 
sets work off of hashes.
same as dicts
 
nvm, got kevin'd
 
5:05 PM
haha
 
Anyway. I don't quite understand why your idea wouldn't work on O loops. Let's use my A & B example from earlier. We don't see A in the dict, so we add it to the dict and continue. We don't see B in the dict, so we add it to the dict and continue. We see A in the dict, so we print "loop detected!" and exit. Success!
 
yes, yes. It would :)
 
If the objection is "actually we start with the node after the root node, so you wouldn't detect A in the third iteration there", it still works, except you exit one iteration later when you see B in the dict
 
Correct
When does the worst case happen for x in s?
where s is a set
they say it's O(n) worst case
 
If each of the set's elements happen to get inserted into the same internal bucket.
I don't know the exact workings, but this basically happens if all of the elments' hashes share some common property.
Hashes are supposed to be well-distributed and random-ish, so it's quite rare for this to happen by coincidence.
 
5:10 PM
@Wis That looks better. It's good that you suggest sys.exit instead of plain exit, maybe also mention why sys.exit is better. BTW, you could probably make your code less verbose by using pathlib instead of the old os.path stuff, but of course that only works in Python 3.
 
I see. Thanks. I will read up on this later. Will go back home now.

Ahh! That is why amazon's dynamo is asking for high cardinality primary keys I suppose
so that they can retrieve by id in O(1)
 
A sufficiently determined bad guy might intentionally choose values that all go in the same bucket, in order to DOS your set-dependent code. But that's quite advanced for an interview question
 
denial of service?
 
And they wouldn't be able to influence the values of this particular set, since you're inserting the ids of objects you've created, which the user has no control over
 
this is interesting
 
5:13 PM
THIS. IS. ROOM. 6!
 
[I kick over a potted plant]
[I apologize to the plant and set it upright]
 
[I nod in approval]
 
You'd never make it in Sparta
 
@Kevin Python hashes of machine-sized integers aren't random: they hash to themself (apart from -1), but that's usually not an issue.
 
room 6 is not suitable for this sort of discussion?
 
5:14 PM
Yeah nah I'm going to be kicking it in Persia. They've got milk and honey.
 
@PM2Ring I don't even know what that means
 
"Can't wait for Xerxes to win the hearts and minds of those poor Spartans"
 
machine sized integers?
 
probably like Tesla sized integer
 
@isquared-KeepitReal No, I was simply responding to your "this is interesting" comment. We try to keep it interesting here, even if the discussion strays a bit from time to time
 
5:16 PM
[nod]
I would like to DOS someone's set-dependent code
that would be a blast
 
@PM2Ring Hmm perhaps I am conflating "hash functions" with "cryptographic hash functions". Continuity might be desirable for the former and fatal for the latter.
I notice that Python mentions at the bottom of docs.python.org/3/reference/datamodel.html#object.__hash__ that it takes measures to avoid hash collision DOSes like the one I described above. But it only works on str, bytes, and datetime.
@ParitoshSingh Probably "any integer smaller than sys.maxsize".
>>> hash(sys.maxsize-1) == sys.maxsize-1
True
>>> hash(sys.maxsize) == sys.maxsize
False
 
@Kevin We do kind of want some randomization, but we get that by doing hashval % hashtable_size, and if there are collision problems, a pseudo-random probing is done to find a slot. There's a brief explanation in the comment at the start of the source. github.com/python/cpython/blob/master/Objects/setobject.c
 
cool, thats pretty nifty
are those maxsize limits just arbitrarily set, or do they have grounds in some genuine architectural limits?
i can get the logic at stopping in powers of 2, so you utilize your bits properly, but is it something other than that as well?
 
The docs say it's the biggest int that a Py_ssize_t can store. IIRC, Py_ssize_t is just an alias for a type from C.
I want to say int but maybe it's uint or something. idk.
 
5:32 PM
>>> import sys
>>> len(bin(sys.maxsize))
65
 
And said type from C usually has grounds in an architectural limit. Something relating to word size probably.
@PaulMcG I'm guessing you have 64 bit Python. I'm using 32 bit and my maxsize has half as many bits as yours.
 
same result here as Paul, 64 bit
 
5:43 PM
@Dodge Sounds like a party. Incidentally, apparently there's an afterparty after the first day now?
 
6:16 PM
How do I raise an error and not have the f-string I used to generate the error text (in all it's parameter exposing and potentially ugly glory)?
eg
    def error_if_equal(a, b):
         if a == b:
                raise ValueError(f'a: {a} equalled b: {b}')
         return f'a={a}, b={b}'

>>> error_if_equal(1, 1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "my_fake_error.py", line 3, in error_if_equal
    raise ValueError(f'a: {a} equalled b: {b}')
ValueError: a: 1 equalled b: 1
 
def error_if_equal(a, b):
    if a == b:
        s = f'a: {a} equalled b: {b}'
        raise ValueError(s)
    return f'a={a}, b={b}'
 
I mean I could generate the string and then pass it to ValueError. But what I'd like is to be able to point the error at the if a== b
 
def error_if_equal(a, b):
    if a == b: raise ValueError(f'a: {a} equalled b: {b}')
    return f'a={a}, b={b}'
Now that I have delivered two flippant half-serious answers, I'll go see if there's any dark magicks that can make fake stack traces
 
I guess I'm wanting just that ValueError: a: 1 equalled b: 1
Much like I get:
int('s')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 's'
...without seeing the inner workings of int, nor whatever f-string or .format created ValueError: invalid literal for int() with base 10: 's'
 
That's easier to accomplish when your function is in C.
 
6:27 PM
@Kevin Making fake stack traces does not feel like the best way to go about it.
@Kevin Learning C does not seem like the Pythonic way...
 
Hmm, it's surprisingly hard to get a traceback object if your program hasn't crashed yet.
 
Hi again, can I count consecutive characters using count function in python?
 
count isn't really built with consecutiveness in mind.
 
Say, I have an input like RRRRR, then the output should be 4 for 4 pairs of consecutive Rs from the left
ok any other short but simple alternative ? @ Kevin
 
@toonarmycaptain Personally I think it's ok to just let the f-string appear in the stack trace, and trust that your users can dig through a stack frame or two to find more useful information about the error.
 
6:31 PM
write one yourself perhaps
 
This...ok so the time I've wasted trying to figure this is embarrassing, but this time has been spent just because I felt like the trace looked...unprofessional, and it seemed like something I should understand. That said, putting the raise with the iflike you said accomplishes what I want.
 
A process that might be as simple as looking up three lines to see that the function is named "error_if_equal"
 
Seeing the f-string and the string it generated is pretty redundant though.
 
I think it's a noble goal to make error messages readable and to cut out unnecessary cruft from the stack trace.
 
@RaphX If you're just looking for matching pairs, you can use zip
 
6:32 PM
... But I don't think Python provides many friendly tools that do that.
 
What about except Exception as e: print(e)?
I mean, if you're talking about hiding the stack trace and just printing the cause of the exception
 
@RaphX To find the number of consecutive letters at the start of a string? I'd probably do something like:
>>> import itertools
>>> s = "RRRRfoobarRRRR"
>>> next(len(list(v)) for k,v in itertools.groupby(s))
4
 
Eg, sum(u==v for u, v in zip(s, s[1:]))
 
Or, hmm, maybe len(list(itertools.takewhile(lambda c: c == s[0], s)))
 
@Kevin That will lookup s[0] on every comparison, though.
 
6:36 PM
print(len(s)-len(s.lstrip(s[0])))?
 
@PM2Ring len(list(itertools.takewhile(lambda c, s0 = s[0]: c == s0, s)))? :-P
 
I just wanted a pretty/informative message with the stacktrace that didn't redundantly expose the mechanics used to produce said string.
I'll be handling and logging any errors anyway, and if a user works out how to pass a type other than `str` to the `name` field, then they knew they were monkeying about in the first place, and in that case I'd like a separate string with expletives to be returned and then brick their machine...but I'm not sure that python has <class Unfriendly> tools for things like that.
 
@Kevin Yeah, ok.
 
RRRRfoobarRRRR should return output as 6 for R for the problem statement I am working on
 
I feel like there's a better way to get the length of a finite iterable besides calling len(list(...)) on it
 
6:39 PM
print(len(s)-len(s.lstrip(s[0]))) doesn't work either
 
I've seen sum(1 for _ in iterable), but meh
 
@RaphX Then the statement you shared isn't right. Cause in no case are there 6 consecutive Rs in any case of that string
 
@RaphX Try it on my code.
 
Oops, looks like I entirely misunderstood the requirements.
Oh well, at least I satisfied the requirements that I made up myself
 
Lol. Ah, no it was just Kevin's fault ;)
 
6:41 PM
Wayne its not 6 consecutive R's that I am counting but no of pairs of RRs
Yeah it works @ PM 2Ring , can you please explain the code?
 
@PM2Ring <-- that's the correct method, then, @RaphX
 
@toonarmycaptain I've used a handful of third-party libraries that redundantly expose the mechanics used to produce the exception string. I consider these libraries to be well-maintained and respectable. So at the very least, take comfort that you are in good company.
 
@PM2Ring off topic, but do you know of a purpose for a Motzkin number / maybe a practical use for this pattern? (The wiki doesn't hold much other than what it is)
 
Learning about Json module now. Quite fascinating
 
:D When I put the raise on the same line as the if in a setter, it prints the self.name = name line and just lists the line number in the setter, with the pretty message.
 
6:46 PM
@RaphX It compares adjacent pairs in the string & counts how many match. Let s='RRRRfoobarRRRR' then s[1:] is 'RRRfoobarRRRR'. The zip function lets us walk over those 2 strings in parallel, so we 1st compare s[0] & s[1], then s[1] & s[2], etc.
 
  File "<input>", line 1, in <module>
  File "Q:\student.py", line 47, in __init__
    self.name = name
  File "Q:\student.py", line 77, in name
TypeError: Student name must be a str,  got <class 'int'> instead.
 
json is pretty lovely
 
Cool, got it, thanks a lot@PM2Ring
 
@toonarmycaptain Is that something you are showing to a user or to a user of your library (i.e. another developer)?
 
@RaphX No worries.
 
6:52 PM
@toonarmycaptain Interesting, must be a new feature. When I try to replicate on 3.6, I get a regular ugly stack trace with the raise included. But when I try on Ideone, the raise isn't present in the stack trace. ideone.com/Xe1epr
 
@MooingRawr Sorry, I've never heard of that term before, although I have played with similar things. I guess there are practical applications, but nothing comes to mind right now. It's getting rather late here, but if I think of something I'll let you know.
 
But, hmm, I'm double confused, because your stack trace shows the line from __init__ that causes the crash, but ideone's doesn't show any lines at all. So now there are three different behaviors on three different environments.
 
Thank sir, I was reading up on the number 9, and I found out about that which made me confused on why it's a thing
 
Maybe ideone just always skips displaying actual code in its stack traces, regardless of whether it's a property that's raising the error.
ideone.com/JRd3tZ is good evidence that this is the case.
 
Automated testing is so wonderful...
 
6:57 PM
This neither confirms nor denies my "3.7 has more concise stack traces for setters" theory but I'm less confident now that I have 2 data points instead of 3
And if the stack trace is only concise when the raise is on the same line as the if, then I'm just totally baffled
 
03:00 - 19:0019:00 - 23:00

« first day (3093 days earlier)      last day (1870 days later) »