I'm trying to solve the following problem:
From the input you will get a number. Find all the ways you can get this number when throwing two dice. Print the result as a list of tuples. In each tuple print the smaller number first. Sort the tuples by the first number. If there is no way to get the given number when throwing two dice, simply print an empty list. With Input: 8 Output: [(2, 6), (3, 5), (4, 4)]
My code is the following:
dice = tuple(n for n in range(0,7))
dice2 = tuple(n for n in range(0,7))
value = int(input())
dice_values = []
def dice_calc(value):
for x in dice:
for x1 in dice2:
if x + x1 == value or x1 + x == value:
dice_values.append((x, x1))
return dice_values
print(dice_calc(value))
but I'm receiving the following output:
[(2, 6), (3, 5), (4, 4), (5, 3), (6, 2)]
How can I modify my code in the way that the output is the same of the requested one?
To be a bit more efficient(actually half the calculations), as you know that the second dice should be larger you can shift the loop:
dice = range(1,7) # you want to start at 1
# dice two will be dynamicly choosen
value = int(input())
dice_values = []
def dice_calc(value):
for x in range(1,7):
for x1 in range(x, 7):
if x + x1 == value:
dice_values.append((x, x1))
return dice_values
print(dice_calc(value))
With list comprehensions you can further improve the performance but on cost on readability.
Output [(2, 6), (3, 5), (4, 4)]