-2

I want to create a program that will take a positive integer n, then create a list consisting of n random numbers between 0 and 9. Once I find that, I want to return the average of those numbers. Am I on the right track?

import random
def randomNumbers(n):
    n > 0
    myList = random.randrange(0,9)

I know I haven't gotten to the second part yet.. but is this how I start out?

This is my final code:

import random
def randomNumbers(n):
    myList = []
    for i in range(n):
        myList.append(random.randrange(0, 9))
    return sum(myList)/len(myList)

Could someone direct me to a page where it talks about a for and while loops and when to use them?

Tonechas
  • 13,398
  • 16
  • 46
  • 80
user2744489
  • 489
  • 1
  • 5
  • 10
  • What do you think is happening on the third line (`n > 0`)? You probably need an [`if`](http://docs.python.org/2/tutorial/controlflow.html#if-statements) statement there. Also, you are not returning anything from the function `randomNumbers()`. You may need to use a [`return`](http://docs.python.org/2/reference/simple_stmts.html#return) statement if you intend to return the list `myList` to the caller of this function. – crayzeewulf Sep 11 '13 at 00:46
  • In the end you'll get `return sum(random.randint(0, 9) for _ in range(n)) / n` ... – Matthias Sep 11 '13 at 05:31

5 Answers5

2

The equals sign (=) is only used to set the value of the "entire variable" (like myList). You want a list, which will then have values added to it, so start with this:

myList = []

to make it an empty list.

Now you had the right idea about repeating something while n > 0- but the ideal way is to use a for loop:

for i in range(n): # repeats the following line(s) of code n times
    myList.append(random.randrange(0,9))

To find the average, take the sum and divide by the number of items (n).

If you are using Python 2.x, then note that an integer divided by another integer will round to an integer, so you should convert into a float (decimal) before division:

average = sum(myList)*1.0/n

For Python 3.x, int/int gives a float like you might expect:

average = sum(myList)/n

To return a value, use the return statement:

return average

SimonT
  • 2,219
  • 1
  • 18
  • 32
1

It helps to break down what you're trying to do, if it's too complicated in a single explanation.

  • Take a positive integer, n
  • create a list of n length
    • each element should be a number 0-9
  • return the average of that list.

Let's tackle this one at a time:

take a positive integer, n

def randomNumbers(n):
    if type(n)==int and n>0:

when you say def randomNumbers(n): you're saying

Hey, computer, this is a function called "randomNumbers",
and it's going to be called with a single thing in parentheses
and we're going to call that `n` from now on.
Here's what that function does:

But you haven't ensured that n is an integer greater than 0. It's just a thing. So we need to ensure that it is. if type(n)==int and n>0: does that by checking that the type of n is int and that n's value is positive (greater than 0).

That's the first bullet point done. Next is creating a list of n length with each element being an integer numbered 0-9. These should be random[1].

result=list()
for i in range(n):
    result.append(random.randint(0,9))

This is less complicated than it seems. You start by creating a list that you'll call result (or whatever you want, I don't care). The for loop is just saying:

Hey, computer, you're gonna do the same thing a number of times,
and that number is "until you've counted from 0 to n times".
And when you do that, "i" is going to represent where you are
in that "0 to n" range. Here's what you're gonna do all those times:

So what are you going to do n times? You're going to append a random integer between 0 and 9 to that list we just called result. That's what result.append(random.randint(0,9)) does.

So next you want to return the average of that list. Well, the average of a list is the sum of the numbers in the list divided by the length.

return sum(result)/float(len(result))

sum and len can take any iterable, like a list, or a set, or whatever you please, and give you the sum, length, or whatever else you ask for. These are great tools to learn about. So do it. Elsewhere, preferably, frankly.

Now, if you've been really attentive, you'll see that so far we have this:

import random # I added this secretly, sorry!
def randomNumbers(n):
    if type(n)==int and n>0:
        result=list()
        for i in range(n):
            result.append(random.randint(0,9))
        return sum(result)/float(len(result))

Which is great! That's what you need; try print(randomNumbers(5)) and you'll get exactly what you're looking for: the average of a bunch of random numbers.

But what if you try print(randomNumbers('foo'))? You probably get None, right? That's because it didn't fit in with the if statement we wrote, and so it never went down that path! You need to write an else statement so things that aren't positive integers still get some love.

else:
    return "That's no good. Try a positive integer instead"

Stupid, but it works. Someday you'll learn about raising exceptions and all that smooth Jazz, but until then, it's fine just to say

Hey, computer, if n wasn't up to my stratospheric expectations,
then just spit back this message. I'll understand.

So at the end of the day you've got

import random

def randomNumbers(n):
    if type(n)==int and n>0:
        result=list()
        for i in range(n):
            result.append(random.randint(0,9))
        return sum(result)/float(len(result))
    else:
        return "That's no good. Try a positive integer instead"

There's some stuff you can do with this code to make it more efficient. To make you curious, I'll give an example:

from random import randint

def randy(n:int):
    return sum({randint(0,9) for i in range(n)})/n if n>0 else "Try again."

That gets into list comprehensions, sets, function annotations, and other stuff that you don't need to worry about. And frankly, that line of code might be too convoluted for good "Pythonic" code, but it's possible, which is cool.

Keep at it, and don't get discouraged. Python makes an effort to explain what you did wrong, and the community is generally pretty good if you've done your due diligence. Just don't abuse them(/us) by asking for help without seeking answers on your own first.

[1]technically they're pseudorandom but true randomness is hard to produce.

Ali Alkhatib
  • 425
  • 2
  • 8
0

You are not on the right track. See this variate for the track.

import random

def randomNumbers(n):
    l = random.sample(xrange(10),  n)
    return sum(l)/len(l)
Community
  • 1
  • 1
Brian
  • 7,394
  • 3
  • 25
  • 46
  • confused on the 4th line why you put the variable "n" in? – user2744489 Sep 11 '13 at 00:58
  • 1
    `n` is the function parameter. Dude, this is your assignment or something? We're not supposed to provide assignment answers. – Brian Sep 11 '13 at 01:00
  • I never asked for the answer to my question. I want to figure it out. I'm a beginner in programming. – user2744489 Sep 11 '13 at 01:06
  • 1
    This won't produce a list of n random numbers... It will select n random numbers from the population sequence (in this case xrange(10)). This means there will be no repeated numbers, and an exception will be thrown if n is larger than 10. – nakedfanatic Sep 11 '13 at 01:27
0

Could be done more concisely with a list comprehension:

myList = [randrange(0, 9) for x in xrange(n)]
average = sum(myList) / len(myList)
nakedfanatic
  • 3,108
  • 2
  • 28
  • 33
0

You should think about making use of Numpy. This would make your task easy.

import numpy as np

def myfunc(n):
    x = np.random.randint(low=0, high=10, size=n)
    return np.mean(x)
Joel Vroom
  • 1,611
  • 1
  • 16
  • 30