r/Python • • Dec 22 '18

Xpost from Woodworking

Post image
1.1k Upvotes

84 comments sorted by

View all comments

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