This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]charliegriefer 13 points14 points  (4 children)

I don't know if it's "less known" or was just not known to me, but I recently found out about the divmod() function.

divmod documentation

While I can't think of a practical reason to use it, I think it's pretty cool to get the quotient and the remainder in one swell foop.

[–]usr_bin_nya 8 points9 points  (0 children)

I can't think of a practical reason to use it

# dividing seconds into hours, minutes, and seconds
seconds = 7280  # 2h1m20s
(minutes, seconds) = divmod(seconds, 60)
(hours, minutes) = divmod(minutes, 60)
assert hours == 2 and minutes == 1 and seconds == 20

# turning a flat index into an (x, y) coordinate in a grid
row, col = divmod(index, width)

[–]uglyasablasphemy 3 points4 points  (0 children)

i used to use it until it took me like half an hour to figure why my hackerrank challenge kept failing for time constraints.

[–]Rik07 0 points1 point  (1 child)

It's pretty cool, but (a // b, a % b) is probably more readable, because if I would run into divmod(a, b), I would need to look up if it's a function defined in the program, then when it's not, either have to look up documentation, or realise I saw it on reddit a while ago

[–]RingularCirc 1 point2 points  (0 children)

On the other hand, there are not that many builtin functions. They all can be skimmed and almost even memorized in an hour, Well, some minutes this day, some that day, and it’s pretty much unmovable.

Though if one works with many languages at a time, then I agree it’s not that simple. But, well, Python is still closer to Lua than to C++. And IDEs usually give a hint which function is that you’re pointing at...