In my code I am attempting to generate 8 random numbers using a for loop. I then add these to the end of my array of the name 'numbers'. Now I will like to add the numbers in this array together but I can't figure out a way to do this.
Below you will see my code.
def get_key():
numbers = []
for i in range(8):
i = random.randrange(33, 126)
numbers.append(i)
get_key()
You want to use sum
a = [1,2,3,4,5]
sum(a) # outputs 15
add as in sum? simply do sum(numbers).
As others have noted, you can use sum to iterate and accumulate over the list (the default accumulator for sum is int(), i.e. 0). Also, if this is the only purpose for the list, you can save memory by using a generator.
import random
get_key = lambda: sum(random.randrange(33, 126) for _ in range(8))
print( get_key() ) # 612
The real question is why are you trying to do this? It seems like there will be a more direct method by using a higher-level distribution. For example, the sum of n I.I.D. variables will approach a Normal distribution.
Related
I’ve been working on a school project and need to do a loop consisting of a couple random numbers but I need them to output a different number each time. The code I’ve been using for the random numbers is this.
import random
a=random.randint(1,9)
I’m new to coding and just starting getting into python for fun and have looked everywhere for how to complete this loop but I can’t find anything that works.I know this code does not include a loop and the loop I was using before was “while True” and “for i in range” Thanks
You have not created any loop yet. You're generating random integer only once.
In order to generate more of them you have to use something like a for loop.
If you're familiar with the concept of range then this is a simple example of generating x-number of random integers.
import random
x = 10
for i in range(0, x):
a = random.randint(1, 9)
print(a)
I am assuming you are doing something like this. Your loop needs to call the random.randint function on each iteration of the loop.
a = random.randint(1,9)
for i in range(5):
print(a)
What you should be doing is this
for i in range(5):
print(random.randint(1,9))
If you want to have 5 values between 1 - 9 without repetition you can use the sample function of the random module. This will select n values from a list and store them in a new list.
array = random.sample(range(1, 9), 5)
for elem in array:
print(elem)
But if you want to have a new random value between 1 and 9 every iteration and you dont care if a number is repeated I would go with the answers the others already gave you.
Random works with a seed, with the same seed the same output
Easiest way to achieve that you want, you will have a different seed each time you run your program
import random
from datetime import datetime
random.seed(datetime.now())
for _ in range(10):
a=random.randint(1,9)
My goal is to generate a series of random numbers without allowing the same number repeating next to eachother but allowing the same number twice like 1,2,1,2 but not 1,1,2,2 and I'm just not really sure how to accomplish this.
Something like this?
import random
list = []
list.append(random.randrange(50))
for i in range(50):
x = random.randrange(50)
while x == list[i]:
x = random.randrange(50)
list.append(x)
print(list)
Also you should post your own attempt. It gives everyone a good reference and starting point to help you out in a meaning full and focused way.
Probably a simple answer, not sure what I am missing. For a homework assignment I have to use random.random() to generate numbers between 30 and 35. The seed has to be set to 70 to match the pseudo-random numbers with the grader. This wasn't in my lecture so I am a little stumped as to what to do.
I have:
import random
def problem2_4():
print(random.random(30,35))
But this is clearly wrong.
The assignment says the output should look like (note: for the problem i use def problem2_4() just for the assignment grading system)
problem2_4()
[34.54884618961936, 31.470395203793395, 32.297169396656095, 30.681793552717807,
34.97530360173135, 30.773219981037737, 33.36969776732032, 32.990127772708405,
33.57311858494461, 32.052629620057274]
The output [blah, blah, blah] indicates that it is a list of numbers rather than a series of numbers printed one-by-one.
In addition, if you want random floating point values, you'll need to transform the numbers from random.random (which are zero to one) into that range.
That means you'll probably need something like:
import random # Need this module.
def problem2_4():
random.seed(70) # Set initial seed.
nums = [] # Start with empty list.
for _ in range(10): # Will add ten values.
nums += [random.random() * 5 + 30] # Add one value in desired range.
print(nums) # Print resultant list.
Of course, the Pythonic way to do this would be:
import random
random.seed(70)
print([random.random() * 5 + 30 for _ in range(10)])
Bit that might be a bit ahead of where your educator is working. Still, it's good to learn this stuff as early as possile since you'll never be a Pythonista until you do :-)
The function that you are looking for is randint, which returns an integer (whole number) between the specified minimum and maximum values.
So the solution would be
random.randint(30, 35)
Python Docs
This question already has answers here:
How can I randomly select an item from a list?
(17 answers)
Closed 7 years ago.
This question could be generalized to randomly creating a list of size n, containing pre-specified integers (assuming a uniform distribution). Hopefully it would look like the following:
Perhaps the syntax would look something like
randList([list of integers], size)
which could then produce something along the lines of:
randList([1,-1], 7)
>>> [1,-1,1,-1,-1,-1,1] #(random)
or
randList([2,3,4], 10)
>>> [4,3,4,2,2,4,2,3,4,3] #(random)
I am a bit new to python and everywhere I look it is always returning a range of values between a low and a high, and not specific values. Thanks
vals = [random.choice(integers) for _ in range(num_ints)]
Here's a fully working example. All you need to do is replace the value of choices with the list of numbers you want to select from and replace range(10) with range(number_of_items_i_want)
import random
choices = list(range(10))
random_sample = [random.choice(choices) for _ in range(10)]
If you want this as a function so that you can reuse it, this would be an easy way to do it:
import random
def random_list(choices, size):
return [random.choice(choices) for _ in range(size)]
You want to use random.choice, see this SO answer for a discussion.
However, even if you could only do values within a range:
I am a bit new to python and everywhere I look it is always returning
a range of values between a low and a high
...You could still do what you want here, just assume the low/high limits to be 0 -> the size of your list, and then with each random int generated in that range, take the number at that index.
I have a problem I attempting to solve this problem.
I have a function that produces tuples. I attempted to store them in an array in this method
while(loops til exhausted)
count = 0
set_of_tuples[count] = function(n,n,n)
count = count + 1
apparently python doesn't store variables this way. How can I go about storing a set of tuples in a variable and then averaging them out?
You can store them in a couple ways. Here is one:
set_of_tuples = []
while `<loop-condition>`:
set_of_tuples.append(function(n, n, n))
If you want to average the results element-wise, you can:
average = tuple(sum(x[i] for x in set_of_tuples) / len(set_of_tuples)
for i in range(len(set_of_tuples[0])))
If this is numerical data, you probably want to use Numpy instead. If you were using a Numpy array, you would just:
average = numpy.average(arr, axis=0)
Hmmm, your psuedo-code is not Python at all. You might want to look at something more like:
## count = 0
set_of_tuples = list()
while not exhausted():
set_of_tuples.append(function(n,n,n))
## count += 1
count = len(set_of_tuples)
However, here the count is superfluous since we can just *len(set_of_tuples)* after the loop if we want. Also the name "set_of_tuples" is a pretty poor choice; especially given that it's not a set.