Question
Create a function (Python) called `histogram` that takes as input a dataset `data`, a lower bound `l`, an upper bound `h`, and a number of
Create a function (Python) called `histogram` that takes as input a dataset `data`, a lower bound `l`, an upper bound `h`, and a number of bins `n`, and returns a histogram representation of `data` with `n` bins between these bounds. More specifically, your function should:
1. Have input arguments `histogram(data, n, l, h)`, expecting `data` as a list of floats, `n` as an integer, and `l` and `h` as floats. 2. Initialize the histogram `hist` as a list of `n` zeros. 3. Calculate the bin width as `w = (h-l)/n`, so that `hist[0]` will represent values in the range `[l, l + w)`, `hist[1]` in the range `[l + w, l + 2w)`, and so on through `hist[n-1]`. (Remember that `[` is inclusive while `)` is not!) 4. Ignore any values in `data` that are less than or equal to `l`, or greater than or equal to `h`. 5. Increment `hist[i]` by 1 for each value in `data` that belongs to bin `i`, i.e., in the range `[l + i*w, l + (i+1)*w)`. 6. Return `hist`.
At the beginning of your function, be sure to check that `n` is a positive integer and that `h >= l`; if not, your code should just print a message and return an empty list for `hist`.
For example, typing in
``` data = [-2, -2.2, 0, 5.6, 8.3, 10.1, 30, 4.4, 1.9, -3.3, 9, 8] hist = histogram(data, 10, -5, 10) print(hist) ```
should return
``` [0, 2, 1, 1, 1, 0, 1, 1, 2, 1]
This is a pretty small problem but I can't seem to code it. Can someone help? Thank you!
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started