Python generating list using for loop, finding maxValue - python

The question is to write a function called randNumMaxFor(n, maxValue), with a for loop that generates a list of n random numbers between 0 and maxValue. I can get the random list generated with a for loop but I have no clue how to get to the next step. Thanks for any hints or tips.
import random
def randomNumbers(n):
#create an empty list
myList=[]
#While loop to create new numbers
for n in range(0,9):
#create a random integer between 0 and 9, inclusive
randomNumber=int(random.random()*10)
#add the random number to the list of random numbers using the append() method
myList.append(randomNumber)
return myList

for loop that generates a list of n random numbers between 0 and maxValue
Your loop doesn't iterate from 0 to n. Replace with this:
for i in range(0,n):
You can use randint() to generate random numbers between 0 to maxValue. It will be something like randint(0, maxValue).
You can then sort the list and return the last value which will be the max value
return sorted(myList)[len(myList) - 1]

import random
def randNumMaxFor(n, maxValue):
ret = []
for i in range(n):
ret.append(random.random() * maxValue)
return ret
>>> randNumMaxFor(5, 100)
[26.72290088458923,
59.19115828283099,
92.35251365446278,
21.0800837007157,
44.83968075845669]

Related

How to get items from a list > than X

I have a function called "first_funtion()" that returns a list of 100 instances of a class.
Then I want to define a second function that is going to create a new list with random instances taken from the output list of first_function(), something like:
first_funtion()
def second_function(list2, N):
list2 = list2(random.choice(first_function()))
The thing is that I want list2 to be always greater than N, so if N = 5 I want the random list2 to be more than 5 instances. If N = 10 then I want the list to be more that 10 instances.
How can I do that?
You can first create the list using first_function, then draw a random integer in the range between N and the length of the list and then draw a random sample from the list.
import random
def second_function(list2, N):
len_list = len(list2)
length = random.randint(N, len_list)
return random.sample(list2, length)
You can do it by using two random function;
Use first one to choose a value of N from the range excluding N to including lenght of list1, i.e, (N, len(list1)]
x = random.randint(N+1, len(list1)
And use second one to choose x number of values from list_1;
random.choices(list1, k=x)
So, the code will look something like this:
import random
def second_function(list1, N):
x = random.randint(N+1, len(list1))
y = random.choices(list1, k=x)
print(y)
Here randint(start, stop) includes both start and stop numbers while generating random integer. It will generate a random number from the inclusive range.
Andrandom.choices () function returns total k number of random items from any list.
Note: You may get repeated values if you're using random.choices (). So, use random.sample() function when you want to choose multiple random items from a list without repetition or duplicates.
You can visit on this link and explore more related to this.
As the random.choice() function always picks one element from the list, so you can iterate through the list more than N number of times and use random.choice() each time. And you can also use random.randint() to get a random number above N, to be used in the range function for the for loop.
import random
def second_function(list2, N):
for i in range(N,random.randint(N,len( first function() ))) :
list2.append(random.choice(first_function()))
return list2

How to generate a random item from a list several times in a row, but everytime it´s a different item generated

I have a list :
x = ["A","B","C"]
and I want to print out a random item a random number of times but every time the random item is generated it should be different for example:
ACBAACBB
what is the simplest way to do that?
This essentially requires two elements of the random package, one to generate a random element from the list x, and the other to generate a random number which would act as the length of the desired output.
import random
x = ["A","B","C"]
r = random.randint(1,100)
st = ''
for i in range(r):
var = random.choice(x)
st += var
print (st)
This generates outputs ranging from 1 to 100 in length. Modify the random.randint(1,100) to get the desired output length.
You can set limits on the length of the string manually, and then choose a random element from the list each time you want a new character using iteration.
The following code will print a string in this format with a minimum range of 1 and a maximum range of 10
import random
x = ["A","B","C"]
text = ""
for i in range(random.randint(1,10)):
text += random.choice(x)
print(text)

How to get the position of a random number generated in a python list.?

I have a numeric list. I need pick a random number in a numeric list and know position number found in list.
random.choice(name_list) just find a random number but I am at the same time in need of a random number position
generate random indexes to use instead.
import random
a = [1,2,3,4,5]
rand_num = random.randrange(len(a))
print(a[rand_num])
You could also get the index and the random number in one operation using enumerate()
index,number = random.choice(list(enumerate(a)))
This not very efficient however and, if you're doing this often or on a very big list, you should do it in two steps
index = random.randrange(len(a))
number = a[index]
import random
sample_list = [1,2,3,4,5]
# this should be work for multiple same value indexes
# EX: sample_list = [1,2,3,2,2]
# if random number is 2 than below code will print indexes 1, 3, 4
random_number = random.choice(sample_list)
for i in [i for i,x in enumerate(sample_list) if x == random_number]:
print(i) # print the indexes or random number

Finding All permutations of a list when given a function that returns the next permutation of a list

In my assignment this week I was asked to write a python script that takes a number n and returns all permutations of [0,1,2,...,n-1]. So far I have written a script that takes a list and returns the next permutation of the list. I am looking for ideas on how I can write the script based on what I've written so far.
def next_permutation(p):
a = len(p)
i = a -2
while i >= 0 and p[i] >= p[i+1]:
i = i-1
if i == -1:
return []
j = i+1
while j < a and p[j] >= p[i]:
j += 1
j-=1
p[i], p[j] = p[j], p[i]
k = i + 1
l = a - 1
while k < l:
p[k], p[l] = p[l], p[k]
k += 1
l -= 1
return p
EDIT: this is the code that returns the next permutation of a list. I wrote this entirely based on the instruction provided by my instructor.
Since you want to have all the permutations of a list with numbers from 0 to n-1, you already have clear steps that you need to take:
Create a list that contains all numbers from 0 to n-1:
This can be easily done with the in-built range() function since it is mostly used for exactly that purpose:
range(stop)
This is a versatile function to create iterables yielding arithmetic progressions.
Calculate the amount of permutations that such list would have:
Math tells us that having N elements, there will be N! different permutations of those elements, wher ! means factorial. We can import factorial function from math module which would quickly allow us to calculate the amount of permutations your list will have:
from math import factorial
print(factorial(4)) # 24
Call your function next_permutation(p) that you already wrote that many times and yield each and every permutation.
To return something more than once from a function, you can use yield insted.
With these steps in mind, you can create something similar to this:
def all_permutations(n):
# Constructing a list that contains all numbers from 0 to n-1
integer_list = list(range(n))
# Calculating the amount of permutations such list would have
permutation_count = factorial(n)
# Output that many permutations
for _ in range(permutation_count):
yield integer_list
integer_list = next_permutation(integer_list)
This generator function will yield all permutations of a list containing numbers from 0 to n-1 which is exactly what you need.
To create a list that would contain all of the permutations you can write something simple like:
n = 4
all_permutations = list(all_permutations(n))

Generating a list of random integers in python 3

I am getting a IndexError: list assignment index out of range error when trying to run this program. My index appears to be fine (0 through 8) and I don't think .append is needed since the equal sign assign the random value each pass. What am I missing?
import random
#The main function.
def main():
#Welcome message.
print("Welcome to the lottery number generator program!")
print()
#Explain what the program does.
print("Note: This program will randomly generate a 7 digit lottery number and display it to the screen. ")
print("________________________________________________________________________________________________")
print()
print()
#Call the generateNumbers function and store its returned list in variable lotteryNumbers.
lotteryNumbers = generateNumbers()
#Call the printLottery function and pass the lotteryNumbers list as argument.
printLottery(lotteryNumbers)
#The generateNumbers function generated 7 random digits between 0 and 9 stores them in a list and returns the list.
def generateNumbers():
#A list variable to hold empty list.
lotteryNumbers = []
#Declare and set loop counter to 0.
index = 0
for index in range (0,8):
lotteryNumbers[index] = random.randrange(0,10)
index += 1
return lotteryNumbers
def printLottery(lotteryNumbers):
print("Here are the 7 lucky numbers: {}".format(lotteryNumbers))
#End main
main()
Lists are not like arrays in other languages!
lotteryNumbers is initialised as an empty list. There is nothing in it. Its length is zero. You need to add random.randrange(0, 10) to the empty list. This is done through .append()
for index in range (0,8):
lotteryNumbers[index] = random.randrange(0,10)
index += 1
This doesn't do what you're hoping it does. You can't assign a value to a position that doesn't currently exist in a list, and as that list is currently empty, that means you can't do this at all.
what you want is:
for index in range (0,8):
lotteryNumbers.append(random.randrange(0,10))
You don't need index += 1 because python handles this for you int the for loop.
by the way, lotteries are generally picked without replacement, so don't you actually want to sample?
https://docs.python.org/2/library/random.html#random.sample
eg:
lotteryNumbers = random.sample(xrange(10), 7)
although it is also normal for lotteries to have far more than 10 options!
By initializing an list with
lotteryNumbers = []
it has exactly 0 elements. But with
lotteryNumbers[index] = random.randrange(0,10)
You try to access the 1st, the 2nd, .. , nth element of the list. Your code does not insert elements to the list. To avoid this there are serveral approaches.
Create a dict instead of a list. A dict actually creates nonexistent elements: lotteryNumbers = {}
Preinitialize the list with 8 elements:
lotteryNumbers = [0,0,0,0,0,0,0,0]
or lotteryNumbers = list(range(8))
But the most preferable variant should be to use append:
lotteryNumbers.append(random.randrange(0,10))
You should append the new values:
def generateNumbers():
#A list variable to hold empty list.
lotteryNumbers = []
#Declare and set loop counter to 0.
index = 0
for _ in range (0,8):
lotteryNumbers.append(random.randrange(0,10))
return lotteryNumbers
or build the list up to the size you want:
def generateNumbers():
#A list variable to hold empty list.
lotteryNumbers = [0]*8
#Declare and set loop counter to 0.
index = 0
for index in range (0,8):
lotteryNumbers[index] = random.randrange(0,10)
return lotteryNumbers
Also notice you dont neet to increment the index, you are already iterating through the range.
You are trying to access non-existing elements of the list.
To build your list, you can either keep appending to it with list.append():
lotteryNumbers = []
for _ in range(8):
lotteryNumbers.append(random.randrange(0,10))
or, as it's common in Python, use a list comprehension:
lotteryNumbers = [random.randrange(0,10) for _ in range(8)]
which is usually more efficient and succinct.
I thinks you try add element to array like
lotteryNumbers = [0,0,0,0,0,0,0]
This works. Make an array with the numbers you want and select randomly one item. Then, delete that item and decrease the length with one (using pop). In this example the numbers 1 till 7
lotteryNumbers = []
rij = []
for i in range(aantal):
rij.append(i)
for j in range(7):
r = random.randrange(0,7-j)
k = rij.pop(r)
lotteryNumbers.append(k+1)
print(lotteryNumbers)

Categories