0

I read a (somewhat) humorous story about the TSA paying a developer $1.4M for an app that simply outputs a random "Left" or "Right" arrow. I decided to try it myself in Python.

I am wondering if I could shorten the if-else statement using something like a Lambda expression or list comprehension... a syntactic shorthand for conditionally printing strings.

import os, datetime, random
while True:
    os.system('clear')
    print "ENTER to continue, or type 'quit'"
    print datetime.datetime.now()
    print ''
    i = random.randint(1,2)
    if i == 1:
        print 'Left'
    else:
        print 'Right'
    print ''
    prompt = raw_input("")
    if prompt == 'quit':
        quit()
nerflad
  • 26
  • 1
  • 5
  • 2
    what about [python ternary operator](http://stackoverflow.com/q/394809/3651800) `print 'Left' if i==1 else print 'Right`. Note that although the requirements sound laughably trivial, depending on the requirements for the true randomness of the distribution it can be more difficult than one might naively think. – Matt Coubrough Apr 04 '16 at 23:54
  • @MattCoubrough that is exactly what I had in mind. I knew I had seen it before. thank you. – nerflad Apr 05 '16 at 00:12

1 Answers1

5

You can use a better random function:

import random
print(random.choice(('Left', 'Right')))

You could also use this trick:

('Left', 'Right')[random.randint(0, 1)]

Which will randomly index into the tuple. Go with choice though.

Check out the docs for random.

Also, the allowance for the TSA app was $360k. See this hackernews comment for a cool breakdown of potential costs.

Josh Smeaton
  • 47,939
  • 24
  • 129
  • 164
  • What makes you say the distribution isn't uniform? That's exactly what I would have expected it to be, so if there's something that suggests otherwise I'd be very interested. – Tom Dalton Apr 04 '16 at 23:58
  • @TomDalton I'll remove that part because I don't know for certain that it's not. The docs don't actually say for the choice function. – Josh Smeaton Apr 04 '16 at 23:59
  • 4
    Minor note: Use a `tuple` literal, not a `list` literal, if you're doing this a lot. The `tuple` would be constructed at load time and reused; the `list` would be constructed at run time every time you make this call, which just adds unnecessary overhead. – ShadowRanger Apr 04 '16 at 23:59