From f45e7b125b8c696ca22c3fcd8999ba41a8c9ff11 Mon Sep 17 00:00:00 2001 From: discretegames <35741644+discretegames@users.noreply.github.com> Date: Fri, 1 Jul 2022 14:55:01 -0700 Subject: [PATCH] Shortened code int(random.random()*number_of_sides)+1 is faster but less "Pythonic", hmm. See https://stackoverflow.com/questions/58124646/why-in-python-is-random-randint-so-much-slower-than-random-random --- higher-of-two-rolls.py | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/higher-of-two-rolls.py b/higher-of-two-rolls.py index e75264b..a796e9a 100644 --- a/higher-of-two-rolls.py +++ b/higher-of-two-rolls.py @@ -1,15 +1,7 @@ -import random - -number_of_sides = int(input("How many sides on your dice? ")) - -sum_of_results = 0.0 - -trials = 0 -while trials < 10**6: - sum_of_results += max([int(random.random()*number_of_sides)+1,int(random.random()*number_of_sides)+1]) - trials += 1 - -print("Average result of rolling two and taking the highest is about {0}".format(sum_of_results/trials)) - +from random import randint +number_of_sides = int(input("How many sides on your dice? ")) +trials = 10**6 +sum_of_results = sum(max(randint(1, number_of_sides), randint(1, number_of_sides)) for _ in range(trials)) +print(f"Average result of rolling two and taking the highest is about {sum_of_results/trials}")