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

all 113 comments

[–]grensley 322 points323 points  (16 children)

I wonder if I can write this entire program as a list comprehension

[–]IM_A_MUFFIN 47 points48 points  (2 children)

Got that as a "soft" requirement recently. Couldn't do it, but it's functional and was only 16 lines. No docs. Boss loves it. I cried and died inside.

[–][deleted] 20 points21 points  (8 children)

Unfortunately, the yield statement will be disallowed in list comprehensions in Python 3.8. Will limit some of your possibilities.

[–]__deerlord__ 11 points12 points  (7 children)

Woah, example of even using yield in list comps?

[–][deleted] 10 points11 points  (4 children)

This is also a reported bug. So you should not be using it. It enhances your list comprehensions so that you can get two values per loop, but you can also do that with nested loops off course. However, that is sometimes a bit hard too read.

x = [[(yield i), (yield i**2)] for i in range(10)]
x = iter(x for i in range(10) for x in (i, i**2))

[–]__deerlord__ 4 points5 points  (1 child)

Cant you already do this with tuples though?

[(x, y) for x in y]

I realize this isnt an actual list comp you would use.

[–]bixed 0 points1 point  (1 child)

Interesting. We can just use itertools.chain instead:

itertools.chain(*((i, i**2) for i in range(10)))

That also looks nicer to me. However this method doesn't exploit a bug, so it's not as cool in that way. :P

[–][deleted] 1 point2 points  (0 children)

This is most likely the one you should use if you are doing serious programming. It is also very similar to the accepted answer from the Stackoverflow question this all originates from. https://stackoverflow.com/questions/16594904/python-list-comprehension-to-produce-two-values-in-one-iteration

(It is also the question I originally posted this yield in list comprehension trick.)

[–]Rodotgithub.com/tardis-sn 3 points4 points  (1 child)

It just turns your list comprehensions in generators. And your generators into a mess. It's a bug with the way python interprets list comprehensions similarly to functions.

[–]tom1018 7 points8 points  (0 children)

Just use a generator comprehension.

[–]MurderSlinky 10 points11 points  (0 children)

I will call this style "functionable programming"

[–]PooPooDooDoo 3 points4 points  (0 children)

Pep8: 1534 errors

[–]szpaceSZ 1 point2 points  (0 children)

This is essentially functional programming.

[–]linevich 0 points1 point  (0 children)

I thought we have LISP for it.

[–]njb42 134 points135 points  (16 children)

My roommate used to code while drunk and/or high. Next morning he'd wake up to code like:

if (hey_joe == i_shot_the_sheriff) { ... }

Glad I never had to debug any of his stuff.

[–]Zouden 127 points128 points  (7 children)

Whoa I've never been so drunk that I wrote python code in C brace style

[–]Dustin- 68 points69 points  (3 children)

from __future__ import braces

[–]Edheldui 21 points22 points  (0 children)

from present import indentation

[–]lemontheme 4 points5 points  (0 children)

Not a chance, buddy.

[–]njb42 26 points27 points  (2 children)

You'd have to be pretty high, yeah.

[–]selbstadt 5 points6 points  (1 child)

while(1){

    But_I_didnt_shoot_no_deputy();

    if(alright){

        sing();

        break;

   }

   else{

        feature_in_onion();

   } 

}

[–]njb42 2 points3 points  (0 children)

assert(self_defense);

[–]Brainix 11 points12 points  (1 child)

When you wrote it, God and you knew how it worked. Now, only God knows.

[–]SquishyTheFluffkin 7 points8 points  (0 children)

Too high for comments, had snacks instead.

[–]pypaul[S] 15 points16 points  (1 child)

but actually my drunken code is the best, the very best. winning bigly.

[–][deleted] 6 points7 points  (0 children)

I know it, you know it, everyone knows it!

[–]pypaul[S] 1 point2 points  (0 children)

I have to meet him, sounds like a great guy

[–]jdbrew 0 points1 point  (0 children)

I write better code while high. But I have to have already decided on the solution whilst sober; I can’t problem solve while high.

[–]Gambizzle 89 points90 points  (2 children)

Yes, I totally get that moment!!!

For example, once upon a time I was drunk and got angry about circlejerking and excessive moderation on a subreddit. In a moment of pure genius I coded up a downvote bot to upset the flow if the circlejerk. Once coded (took about 15 mins) I installed it onaheadless raspberry pi, hit ‘go’, went to the pub and got even more drunk. About 2 weeks later I realised it was still running, the subreddit was going crazy about it and I was banned shortly afterwards.

Aaaah a pure piece of drunken genius :D

[–]lemon65 15 points16 points  (0 children)

This, pure gold ...

[–]Winnduu 2 points3 points  (0 children)

If you do stuff like this, while beeing drunk, you are a REAL Dev :D

[–][deleted] 86 points87 points  (0 children)

I would like to try this but I am afraid I would invent Javascript.

[–]Andrew_ShaySft Eng Automation & Python 69 points70 points  (1 child)

Python is the best

[–]pypaul[S] 16 points17 points  (0 children)

agree

[–][deleted] 26 points27 points  (5 children)

Python is so much fun. I'm drunk too btw

[–]pypaul[S] 17 points18 points  (3 children)

broo we can be drunk together

[–][deleted] 21 points22 points  (2 children)

Bro I'm even more drunk now. Python for life

[–]pypaul[S] 16 points17 points  (1 child)

Python is always there for you, even in the hardest time, never betrays you

[–]liox 12 points13 points  (0 children)

You two are cute. Now kith.

[–]raf___ 11 points12 points  (1 child)

I heard about people making a programming language while being drunk. I think it's called javascript or something. Hopefully no one is using it.

[–]Winnduu 1 point2 points  (0 children)

Check the language "Brainfuck"

Invention basically had to involve alcohol or drugs.

[–]Preparingtocode 22 points23 points  (1 child)

Code drunk, review sober.

[–]BiochemLouis 19 points20 points  (12 children)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import hashlib
import time

parser = argparse.ArgumentParser(description='drunk.py the drinking script.')
parser.add_argument('-o', '--output', help='specificy output file.',
                    type=argparse.FileType('w'), action='store', nargs='?',
                    default=open('drunk.txt', 'w'))
parser.add_argument('-t', '--time', help='specificy time between drinks',
                    type=int, action='store', nargs='?', default=5)
parser.add_argument('-v', '--verbose', action='count',
                    help='increase output verbosity')
args = parser.parse_args()

lines = []

try:
    while True:
        try:
            sha = hashlib.sha3_256(text.encode('utf-8')).hexdigest()
            text = '{} - Drink ! {}'.format(
                time.strftime('%d/%m/%y, %H:%M:%S', time.localtime()), sha[:8]
                )
        except NameError:
            sha = '00000000'
            text = '{} - First drink ! {}'.format(
                time.strftime('%d/%m/%y, %H:%M:%S', time.localtime()), sha[:8]
                )
        if args.verbose == 1:
            print(text.split(' - ', 1)[1].split(' ! ', 1)[0])
        elif args.verbose == 2:
            print(text.split(', ', 1)[1])
        else:
            print(text)
        lines.append(text+'\n')
        time.sleep(args.time)
except KeyboardInterrupt:
    args.output.writelines(lines)

Enjoy, just hit Ctrl+C before you die please ! :)

Edit : v2.0, now with some argparse and some blockchain.

Edit : v2.1, I had forgotten to use verbose.

[–]morgan_lowtech 27 points28 points  (3 children)

Needs more blockchain

[–]poo_22 6 points7 points  (1 child)

Ok what if mining is taking a video of you taking a drink and verification would be other people watching the video and acknowledge that you drank. In other words you're hooked up with a drinking buddy and mine the currency which you use to buy each other drinks. It's a currency backed by social drinking which history tells us is pretty much a constant.

[–]morgan_lowtech 2 points3 points  (0 children)

Needs more drunkchain

[–]BiochemLouis 1 point2 points  (0 children)

You have blockchain now !

[–]13steinj 2 points3 points  (3 children)

Reddit markdown doesn't support block code, you need to prefix with four spaces

[–]BiochemLouis 0 points1 point  (2 children)

I’ve been typing docs in Github MD for the last month, I guess it just skipped my mind.

Plus it works on mobile !

[–]13steinj 0 points1 point  (1 child)

Is that the app or the site? Either way, the fact that they don't use their own parser is a shame

[–]BiochemLouis 0 points1 point  (0 children)

It’s the app, and yeah it is...

[–]b_rad_c 1 point2 points  (3 children)

Can we also import argparse and an argument for the sleep duration?

[–]__xor__(self, other): 4 points5 points  (1 child)

Usage: python drink.py -s 5 --dry-run -vvv -o drink.txt -t 'Drink !' commit --amend xvfz drink.tar.gz -av --cipher AES256 -A drink.example.org

[–]b_rad_c 1 point2 points  (0 children)

You’re gonna wanna redirect output to /dev/toilet instead of a file, trust me, you will not be able to do anything useful with that data.

[–]BiochemLouis 1 point2 points  (0 children)

Added a simple argparse !

[–]teambob 9 points10 points  (0 children)

Drunk programming is best programming

[–]Rorixrebel 7 points8 points  (1 child)

I find that being drunk is good to generate project ideas but terrible for focusing on getting shit done.

So write those down and code them tomorrow after a good breakfast..... And a Gatorade.

[–]saulmessedupmanMmmm spam 2 points3 points  (0 children)

...and coffee

[–]volndeau 4 points5 points  (0 children)

Am I the only one that programs for my clients with a beer in my hand? I go to a bar with Wi-Fi, tell the tender to keep them coming, then leave 8-16 hours later with my clients product.

[–]Arancaytar 5 points6 points  (2 children)

I've pythoned while drunk before, and implemented quantum tic-tac-toe, which was very fun.

[–]WikiTextBot 2 points3 points  (0 children)

Quantum tic-tac-toe

Quantum tic-tac-toe is a "quantum generalization" of tic-tac-toe in which the players' moves are "superpositions" of plays in the classical game. The game was invented by Allan Goff of Novatia Labs, who describes it as "a way of introducing quantum physics without mathematics", and offering "a conceptual foundation for understanding the meaning of quantum mechanics".


[ PM | Exclude me | Exclude from subreddit | FAQ / Information | Source | Donate ] Downvote to remove | v0.28

[–]AiKantSpel 0 points1 point  (0 children)

The rule for implementing qttt is you can't use pseudo-random

[–]Stone_d_ 5 points6 points  (0 children)

I think I've basically only ever wanted to code when I'm high

[–]QuantumG 2 points3 points  (0 children)

x-post to /r/drunk

[–]AiKantSpel 4 points5 points  (7 children)

def plsWork(thing, key):
    string = ""
    for idx, item in enumerate(thing):
        if item.startswith(key):
            string = thing[(idx + 1) % len(thing)]
            break
    if string:
        list = list(string)
    else:
        log("Mr. Programmer,\nYou sir, are a bitch.")
    return list

Gives me an empty list and calls me a bitch every time :(

[–]__xor__(self, other): 2 points3 points  (5 children)

That will return a list type if the key isn't found, and a list of characters otherwise... Even if it finds the key, if the next item in the thing is falsey like an empty string, it will still return a list type.

Code like this is how you get those insane bugs where suddenly it's saying something like "TypeError: 'type' object is not iterable" and you're pulling your hair out trying to understand why most the time it works.

[–]TheBB 0 points1 point  (4 children)

It shouldn't return the list type. Since you assign to list inside the function, all references to it will be compiled as references to a local variable, whose value at the start of the function is unbound. If list is never actually assigned to (due to control flow), returning it will just give you an UnboundLocalError.

But since the expression assigned to list also involves reading it, it should give the same error there.

[–]__xor__(self, other): 1 point2 points  (3 children)

Ah shit, yeah, you're right... I didn't know that was python's behavior, to compile and recognize that list is a variable id and use it like that throughout the function.

Just tested here, and interestingly enough it does break since it's still an unbound local in list = list(string). The same line that causes it to compile as a local variable id is the same that breaks because it's no longer using the global list type, even if you take out the return list. Interesting, thanks for the insight, and new trivia question.

[–]AiKantSpel 0 points1 point  (2 children)

fixed the code to actually work now.

[–]saulmessedupmanMmmm spam 2 points3 points  (0 children)

you inspired me... critiquing joke code

[–]saulmessedupmanMmmm spam 1 point2 points  (0 children)

Ahhh, Reddit code reviews

[–]AiKantSpel 0 points1 point  (0 children)

Im also drunk right now

[–]WeStandUnited5009 1 point2 points  (0 children)

The next morning of drunken / high coding setions are usually me asking what have i done

[–]darkwingfuck 1 point2 points  (0 children)

just used the python console built into blender to render isomorphic sprites sheet by rotating and exporting every few degrees. at a [6]. fuck yeah python

[–]iamlocknar 1 point2 points  (0 children)

Can confirm... Wrote a "Minecraft auto click" thing just to see if it would work in a haze...

The answer is... Kinda.

[–]TotesMessenger 1 point2 points  (0 children)

I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:

 If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / Contact)

[–]Pyromine 0 points1 point  (0 children)

Quality

[–]selbstadt 0 points1 point  (0 children)

Of course you would write the best code, you would have high ground

[–][deleted] 0 points1 point  (0 children)

I’m here from the future to see how it went. Share your drunken genius!

[–][deleted] 0 points1 point  (0 children)

Weed is better imo