-2

How would I be able to improve the speed of this monty hall program, interestingly, the same code written using BBC BASIC for Windows completes the task in half the time of the Python code.

Python Code:

import random

t = 10000001
j = 0
k = 0

for a in range(1, t):
    p = int(random.random() * 3) + 1
    g = int(random.random() * 3) + 1

    if p == g:
        r = int(random.random() * 2) + 1
        if p == 1:
            r += 1
        if p == 2 and r == 2:
            r = 3
    else:
        r = p ^ g
    s = g
    f = g ^ r
    if s == p:
        j = j + 1
    if f == p:
        k = k + 1

print(f"After a total of {t - 1} trials,")
print(f"The 'sticker' won {j} times ({int(j/t*100)}%)")
print(f"The 'swapper' won {k} times ({int(k/t*100)}%)")

BBC BASIC for Windows code

T% = 10000000

for A% = 1 to T%
  P% = rnd(3)
  G% = rnd(3)
  if P% = G% then

    R% = rnd(2)
    if P% = 1 then R% += 1
    if P% = 2 and R% = 2 then R% = 3
  else
    R% = P% eor G%
  endif
  S% = G%
  F% = G% eor R%
  if S% = P% then J% = J% + 1
  if F% = P% then K% = K% + 1
next

print "After a total of ";T%;" trials,"
print "The 'sticker' won ";J%;" times (";int(J%/T%*100);"%)"
print "The 'swapper' won ";K%;" times (";int(K%/T%*100);"%)"
2
  • 2
    Are you asking for code review? Commented May 12, 2017 at 15:09
  • Thank you for pointing me in the direction of code review Commented May 12, 2017 at 15:16

1 Answer 1

1

First thing is changing your import from:

import random

to

from random import random

then using:

p = int(random() * 3) + 1
g = int(random() * 3) + 1

Second thing you can do is change your:

if s == p:
     j = j + 1
if f == p:
     k = k + 1

Into:

if s == p:
     j = j + 1
elif f == p:
     k = k + 1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.