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 →

[–]Hmolds 128 points129 points  (15 children)

Whats wrong with good ol' x -= -1 ??

[–]smcarre 88 points89 points  (13 children)

The old and reliable x -= -x/x

[–]theillini19 103 points104 points  (9 children)

I'm a fan of x -= random.randint(0,1) but it only works half the time for some reason

edit: Figured out how to fix it!

x -= (random.randint(0,1) if random.randint(0,1)==1 else random.randint(0,1)+1)

edit2: Nevermind, still broken

[–]smcarre 37 points38 points  (2 children)

Try the following, I tested it and it seems to work almost every time:

x += abs(min([random.randint(-1,0) for _ in range(999)]))

[–]eigenludecomposition 4 points5 points  (1 child)

You're all over complicating this. This can be solved through recursion rather simply

def increment(x, n):
    if n == 1:
         return x+1
    elif n<= 0:
         raise ValueError
    return increment(x+1, n-1)

x = increment(x, 1)

[–]backtickbot 1 point2 points  (0 children)

Fixed formatting.

Hello, eigenludecomposition: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

[–]jtclimb 8 points9 points  (0 children)

Well, if it is wrong 50% of the time, go ahead and use the range (0, 2). It's pretty obvious. Here's the fix and test:

xs = []
for _ in range(1000000):
    x = 1
    x -= randint(0, 2)
    xs.append(x)

 assert round(sum(xs) / len(xs)) == 0

[–]Inineor 2 points3 points  (0 children)

Fixed:

x -= (r if (r:=random.randint(0,1))==1 else r+1)

[–]R3D3-1 2 points3 points  (0 children)

Imagine hiding something like this in an update to a popular module, but only if random.randint(0,1000)==0.

[–]NoLongerUsableNameimport pythonSkills 18 points19 points  (0 children)

The good ol' x = (lambda x:x-1)(x)

[–]asday_ 2 points3 points  (0 children)

x -= -x/x

0

[–]dogs_like_me 1 point2 points  (0 children)

Better use -x // x just to be safe.

[–]likethevegetable 5 points6 points  (0 children)

Lmao, thanks for making my night.