Issue
I'm using plotly to create a histogram of the results from rolling a 6-sided die 1,000 times.
In die_visual.py, under the "# Visualize the results" comment, I assign a list to the x_values variable.
The list contains the range (1, die.num_sides+1). What is the purpose of the '+1'? To me it seems that since die.num_sides has a default value of 6, the '+1' would increase the end value of the range to 7. I have included the contents of both files below.
die.py:
from random import randint
class Die:
"""A class representing a single die."""
def __init__(self, num_sides=6):
"""Assume a 6-sided die."""
self.num_sides = num_sides
def roll(self):
"""Return a random value between 1 and number of sides."""
return randint(1, self.num_sides)
die_visual.py:
from plotly.graph_objs import Bar, Layout
from plotly import offline
from die import Die
# Create a D6.
die = Die()
# Make some rolls, and store results in a list.
results = []
for roll_num in range(1000):
result = die.roll()
results.append(result)
# Analyze the results.
frequencies = []
for value in range(1, die.num_sides+1):
frequency = results.count(value)
frequencies.append(frequency)
# Visualize the results.
x_values = list(range(1, die.num_sides+1)) <---
data = [Bar(x=x_values, y=frequencies)]
x_axis_config = {'title': 'Result'}
y_axis_config = {'title': 'Frequency of Result'}
my_layout = Layout(title='Results of rolling one D6 1000 times',
xaxis=x_axis_config, yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d6.html')
Any help in understanding this is greatly appreciated. Thank you.
Solution
range(a, b)
gives an output of Range(a, a+1, a+2, ..., b-1)
so range(a, b+1)
gives Range(a to b)
.
One of the reasons for this is that if you want to iterate over the indexes of a list, the length of the list is 1 higher than the last index so range() only going to b-1 makes sense for this.
Answered By - Lecdi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.