Reputation: 23
This is for a programming class using python2. Instructions are to simulate rolling a pair of die 1000 times, store the results in a list and display the percentage of time each roll occurs.
Example of what output should be:
Here's my current code:
#!/usr/bin/python
import random
rolls = [0]*12
for v in range(1000):
d1 = random.randint(1,6)
d2 = random.randint(1,6)
rolls[d1 + d2 -1] += 1
print("Rolled %s %d times, or %.2f %" % (str(rolls)))
Right now I'm getting "TypeError: not enough arguments for format string".
I realize that I need to define a reference for %d and %.2f (and I realize that using %'s is going the way of .format, but this is how the professor has asked for it - hasn't taught how to use .format). I'm not sure how to reference the %d and the %.2f.
I know the %d needs to be a count of how many times a certain number was rolled, but am stuck at how to define and reference it. The %.2f needs to use the definition for the count/1000.
So, I think in my print line I need something like
print("Rolled %s %d times, or %.2f %" % (str(rolls), count, count/1000))
Any insight/corrections would be appreciated.
Upvotes: 2
Views: 3539
Reputation: 71
The first answer is not 100% correct because he/she added is returning or setting default to 1 and then adding another one which is incrementing total count. Total count will be over 1000 in that case. Here is the correct code:
for _ in range(1000):
d1 = random.randint(1,6)
d2 = random.randint(1,6)
results[d1+d2] = results.setdefault(d1+d2, 0) + 1
for roll, count in results.iteritems():
print('Rolled %d %d times, or %.2f %%' % (roll, count, count/1000))
Upvotes: 0
Reputation: 7124
This is covered in the Python Docs: http://docs.python.org/2/library/stdtypes.html#string-formatting
But for each %
you need a value to substitute in:
for roll_value, roll_count in enumerate(rolls):
print "Rolled %s %d times, or %.2f %%" %((roll_value+1), roll_count, (roll_count/1000.)*100)
*note the %%
to print out the %
sign, and the 1000.
to return a type float
Upvotes: 1
Reputation: 174622
A dictionary would be another option, and it would look like this:
import random
results = {}
for _ in range(1000):
d1 = random.randint(1,6)
d2 = random.randint(1,6)
results[d1+d2] = results.setdefault(d1+d2, 1) + 1
for roll, count in results.iteritems():
print('Rolled %d %d times, or %.2f %%' % (roll, count, count/1000.))
setdefault
will set a key to a value if it doesn't exist, otherwise it will return the value of the key.
Upvotes: 0