r/Python • • Dec 22 '18

Xpost from Woodworking

Post image
1.1k Upvotes

84 comments sorted by

369

u/lelease Dec 22 '18

print(random.choice(action))

60

u/callmelucky Dec 22 '18

Also that name should really be actions, plural.

73

u/anyfactor Freelancer. AnyFactor.xyz Dec 22 '18 edited Dec 22 '18

Ah, one of life's more important lessons. No matter how long your script is there will always be someone who can create a single line code that does all of that.

There will be also be someone who will top him by writing a single line functional haskell and say his is more efficient.

0

u/[deleted] Dec 22 '18

[deleted]

5

u/Ph0X Dec 22 '18

Absolutely. It's not about being shorter, but about being more explicit. The problem with a lot of people coming from C-like languages is that they want to do everything with indices. You will see so many range(len(list)) out there.

1

u/a_monkey666 Dec 24 '18

Asking just to learn, but what's the better way? With `enumerate`?

1

u/Ph0X Dec 24 '18

Indeed. Most of the time when people use len-range, they either access just the items, or both index and items. In the rare case where you only need the index, I would still say for i, _ in enumerate(items): is cleaner

7

u/anyfactor Freelancer. AnyFactor.xyz Dec 22 '18

I was just joking, dude. Python with it's standard library is pretty readable.

4

u/[deleted] Dec 22 '18

Oh my bad dude. I think was right before bed and I probably should have been sleeping.

There are people who "pythonize" stuff, like their list comprehension. Which is super concise but I still have a hard time reading.

2

u/SleepyHarry Dec 22 '18

Yeah coding on citrus can be really difficult. Creates some really zesty code. Really rinds my gears.

60

u/primitive_screwhead Dec 22 '18

And just for completeness, random.randrange(len(action)) , if you actually need the index value.

0

u/[deleted] Dec 22 '18

[deleted]

7

u/Ph0X Dec 22 '18

It's not at all about making it shorter, but rather about using the more explicit and appropriate calls. It's like people doing:

for i in range(len(items)):
    print items[i]

instead of

for item in items:
    print item

They are both more or less the same length, but one is far cleaner, Pythonic and explicit.

3

u/primitive_screwhead Dec 22 '18

Like how?

15

u/[deleted] Dec 22 '18

lambda action : random.randrange(len(action))

( ° ͜ʖ °)

18

u/primitive_screwhead Dec 22 '18

An unassigned anonymous function? You're fired. :)

15

u/[deleted] Dec 22 '18

random_randrange_len = lambda action : random.randrange(len(action))

fixed it boss

5

u/galan-e Dec 22 '18

still bad practice according to pep8

14

u/lukaz247 Dec 22 '18

import random
print(random.choice(['slice','chop','dice']))

3

u/AlphaGamer753 3.7 Dec 22 '18

Actually, secrets.choice(action) would be better to use just as a matter of general practice. I avoid random wherever possible, even if it's not necessary.

3

u/lvc_ Dec 23 '18

I was going to post why I disagree with this but then I thought about it and +1 instead. Using cryptographocally secure randomness by default unless you deliberately want the reproducibility of a seedable PRNG is a position that's well worth encouraging. Especially since I have occasionally seen arguments of the opposite form like "no my password generator doesn't need to be cryptographically secure so why should I bother?".

2

u/AlphaGamer753 3.7 Dec 23 '18

That's precisely what I'm encouraging! Thank you.

2

u/MattR0se Dec 22 '18

THANK YOU

1

u/[deleted] Dec 22 '18

You read my mind. Didn't you??

12

u/ReaverKS Dec 22 '18

print(random.choice([‘yes’]))

5

u/import_antigravity Dec 22 '18

+/u/compilebot Python

print(random.choice(['yes']))

1

u/ydepth Dec 22 '18

Would from random import choice

Be better?

5

u/Jam-17 Dec 22 '18

To quote the Zen of Python

Namespaces are one honking great idea -- let's do more of those!

The random prefix helps disambiguate the function name

-4

u/jfleit Dec 22 '18 edited Dec 22 '18

the real life pro tips are always in the comments

edit: damn what did i do to deserve this

-2

u/[deleted] Dec 22 '18

You can beat OP's 15 year old daugther at writing trivial scripts, you must be feeling proud of your merits.

104

u/campbellm Dec 22 '18

Ignore the snarky comments here; as an also wannabe woodworker, this is adorable.

25

u/[deleted] Dec 22 '18

I agree.

As Pythonic as that snark is, this is purely adorbable and I'd love one.

...May have to steal it.

2

u/[deleted] Dec 22 '18

Yes, I can't believe that a smart-arse comment showing a shorter version of the script, as saying look ma, I can write more pythonic code (compared to 3 simple lines written by a teenager) is getting above 300 upvotes. Should expect less of people.

1

u/Theoz Dec 22 '18

Will you explain? I'm new. I know len and random and [ brackets] for lists but that's it. It looks like it's counting the length of cut chop dice but I don't really know

6

u/halooooom Dec 22 '18

The explanation of the snarky comments is that the python code shown is not very Pythonic as its not as readable as possible. In other languages this is the normal solution to select a random item from a list but python already has this function natively.

1

u/Theoz Dec 22 '18

Nice. Thanks!

0

u/pie3636 Dec 22 '18

It displays randomly one of the three actions (slice / chop / dice)

62

u/Undercoversongs Dec 22 '18

Not using random.choice smh

11

u/iamapieceofcheese Dec 22 '18

So inefficient

2

u/Luke_myLord Dec 22 '18

Can you elaborate?

8

u/iamapieceofcheese Dec 22 '18

n = random.randint(0, len(action)-1)

print(action[n])

takes 2 lines of code, but you can just use

random.choice(action)

If I were to write the code in the picture, I would use

import random

print(random.choice(['slice', 'chop', 'dice']))

10

u/primitive_screwhead Dec 22 '18

"so inefficient" doesn't usually apply to using an extra line of code. FWIW, the main efficiency benefit of random.choice() is that it's arguments are easier to parse than randint().

3

u/iamapieceofcheese Dec 22 '18

Oops, sorry

4

u/primitive_screwhead Dec 22 '18

No worries; I'm just adding some sizzle. Your suggestions are perfectly fine, though it might make the cuttingboard too "sparse"... I think we all agree that the aesthetic was the most important issue as to how this particular code was written. :)

3

u/iamapieceofcheese Dec 22 '18

True, the board does look nicer with the current code

2

u/Ph0X Dec 22 '18

To be clear, it's not so much about using more lines of code. It's about using the right APIs and being more explicit about what you're doing. I often write code out to use more lines of code if it makes the code cleaner and more explicit. The other one is inherently easier to read and follow the logic.

1

u/Luke_myLord Dec 22 '18

Totally agree! I thought you were talking about not using .choice

44

u/kashmill Dec 22 '18

Requesting changes: Missing spaces after the , in the list and the parameters. Missing spaces around the -. Fails PEP8 check.

-2

u/BRENNEJM Dec 22 '18

PEP8 wants spaces like that? Weird. I never include spaces there.

13

u/zoomertherumour Dec 22 '18

A comma without a space has no place in this universe.

4

u/BRENNEJM Dec 22 '18

Except here apparently:

Yes: foo = (0,)
No: bar = (0, )

2

u/Ph0X Dec 22 '18

tbf that's one of my least favorite syntaxes, though I see the need. I always feel strange when I see items + (item,)

Sometimes I wonder how i'd look if tuples had similar .append and .extend but instead returned a new tuple

1

u/primitive_screwhead Dec 22 '18

if tuples had similar .append and .extend but instead returned a new tuple

That breaks the principle of least surprise, imo. (because it's arbitrarily different from lists)

2

u/zoomertherumour Dec 22 '18

Actually prefer the latter.

3

u/alkasm github.com/alkasm Dec 22 '18

Which one, after the comma or around an operator? PEP8 suggests both but I disregard the one about operators. I do use spaces for add and subtract, but not for multiply and divide...just too far off from mathematics for me at that point.

2

u/BRENNEJM Dec 22 '18

I don’t use them in lists. It sounds like we write math the same.

According to PEP8 I shouldn’t be using mixedCase to name everything either. Maybe this weekend is a good time to finally read through PEP8.

2

u/alkasm github.com/alkasm Dec 22 '18

Yes, lowerCamelCase is super annoying to most Python programmers, lol!

Remember though, PEP 8 is suggestions. For small things like spacing, use what works for you. It is more important to be consistent. But being consistent with other projects is a nice feature, in which case following PEP 8 more strictly is likely to get you there.

1

u/pm-me-a-pic Dec 22 '18

You need a better ice and/or pre-commit hook with linter

1

u/kashmill Dec 22 '18

Honestly not sure. Flake8 would complain in this context

6

u/[deleted] Dec 22 '18

Best sister ever

3

u/JuliusCaesar000 Dec 22 '18

Thats really cute

5

u/beatryder Dec 22 '18

I would buy this as a gift for a colleague

7

u/[deleted] Dec 22 '18

Same! Especially with the code as is instead of using random.choice() so I could watch their eyes twitch between appreciation and desire to change the code

2

u/tdobzhansky Dec 22 '18

I don't think a stochastic approach to food preparation is a great idea, but then again at least he's actually preparing his own food.

2

u/lwrightjs Dec 22 '18

went to 12 week python bootcamp

can't get a job so pwns 15 y/o's heartfelt work

Hashtag new-age programmers

1

u/LiquidSubtitles Dec 22 '18

Spent a few hours figuring out that the package I was using used both random and numpy.random so that even that even when I saved the numpy seed I couldn't reproduce my results. I now get mildly angry whenever I see random..

Anyway cool wood!

1

u/sezar13 Dec 22 '18

This is a game i created on python while my professor asked me to make something that i liked : from random import choice

play = True

choices = ["rock", "scissors", "paper"]

Compares two choices, returns true if the first wins

False, if the second wins

None if the two are equal

def compare(a, b): if a == b: return None elif (choices.index(a) + 1) % len(choices) == choices.index(b) or
(choices.index(a) + 3) % len(choices) == choices.index(b): return True else: return False

1

u/fauks_of_tenebrae Dec 22 '18

this is beautifully touching

1

u/itsoverlywarm Dec 22 '18

Can someone run through the logic behind this algorithm please ?

1

u/virt1028 Dec 22 '18

Where to buy though?

1

u/Earthling1980 Dec 22 '18

Oh ruby how I love you. [ ‘slice’, ‘dice’, ‘chop’ ].shuffle.pop

1

u/the-kind-against-me Dec 22 '18

hashtag pylint disable=no-space-after-comma

-13

u/deejpake Dec 22 '18

Am I the only one who doesn’t get it?

17

u/ELlisDe Dec 22 '18

It is a cutting board fam

0

u/[deleted] Dec 22 '18

[deleted]

7

u/nerdmor Dec 22 '18

from random import choice

16

u/artificialignorance Dec 22 '18 edited Dec 22 '18
print(__import__('random').choice([‘slice', 'chop', 'dice’]))

4

u/haliax69 Dec 22 '18

TIL I can import modules this way. Thanks!

6

u/Ph0X Dec 22 '18

Please don't. It's good to know, but almost never the right choice.

And if you need dynamic imports, use importlib instead.

1

u/haliax69 Dec 22 '18

Oh, I kinda figured that, but it's nice to use when running commands directly from the command line like:

python3 -c "print(__import__('datetime').datetime.now().strftime('%d, %b %Y'))"

3

u/Ph0X Dec 22 '18

Well on there you can use semicolon, that's still probably cleaner

python3 -c "import datetime; print(datetime.now().strftime('%d, %b %Y'))"

1

u/haliax69 Dec 22 '18

Learned something else today: semicolon = new line. Thanks man!

Just out of curiosity, is there something that replaces indentation?

0

u/[deleted] Dec 22 '18

[deleted]

2

u/wrboyce Dec 22 '18

Not only are your comments excessively verbose, they are incorrect. The second line isn’t casting anything, don’t use words you don’t understand or you’re likely to use them wrong. Same for the third line, no casting.

21

u/[deleted] Dec 22 '18

[removed] — view removed comment

14

u/primitive_screwhead Dec 22 '18

programmer her self!

You know you've written a lot of Python when you split "herself" into "her self" out of habit. ;)

20

u/MattR0se Dec 22 '18

self.her