This is my code and im trying to select 5 items from the 'ticket' list and create a winning combination, but the function sample doesn't seem to be working.
It returns the following:
AttributeError: 'builtin_function_or_method' object has no attribute 'sample'
This is pretty weird as the program does use the random library to correctly generate the ticket.
from random import *
#This function will split the input name into characters and return it as a list
def split(word):
return [char for char in word]
#This function will generate the remaining numbers missing from the maximum number of characters (in this case 13)
def ticket_generation(name, number_of_characters):
#Ticket
ticket = split(name)
#Checking whether all the remaining numbers are generated
while len(ticket) < number_of_characters:
number = randint(0,50)
ticket.append(number)
winning_combination = random.sample(ticket, k=5)
return(ticket)
return(winning_combination)
print(ticket_generation("Leonardo", 13))
You can just remove random. since you've imported the entire package
winning_combination = sample(ticket, k=5)
Otherwise, don't import the entire package
from random import randint, sample
winning_combination = sample(ticket, k=5)
You have imported all from random. No need to write random.sample(,,,) simple sample (,,,) should work.
winning_combination = sample(ticket, k=5)
Related
I'm trying to have random integers between (1,5) but the catch is displaying all of the values from the random integer in a for loop ranging of 10 loops. I only have access to randint() and random() methods in 'random class'.
from random import randint
eventList = []
taskList = []
dayList = []
def getEventList():
eventList.sort()
return eventList
def getTaskList():
return taskList
def getDayList():
return dayList
def generateData():
while len(getTaskList()) < 10:
# Need to implement a way to stretch the random int while having all the integers present
randomEvent = randint(1, 5)
randomTask = randint(10, 30)
randomDay = randint(1, 9)
eventList.append(randomEvent)
dayList.append(randomDay)
if randomTask not in getTaskList():
taskList.append(randomTask)
Based on clarifications in my other answer, I think you meant to ask "how to I get random numbers that fully cover a range?"
You are using randint, and just calling it extra times hoping to get all the values. But depending on random chance, that can take a while.
It would be better to just take all the values you want, e.g. list(range(1,6))
and then just rearrange that with random.shuffle
https://docs.python.org/3/library/random.html#random.shuffle
import random
values = list(range(1, 6))
random.shuffle(values)
print(values)
Obviously, if this is what you want to do, but your prof says you can't use that function, then you should use that function, get working code, and only THEN write your own replacement for the standard library. (so you only have to debug one or the other)
So write your own version of shuffle. I'll leave the details to you, but it should be pretty easy to use randint to pick one of the available entries, removing it, and so on.
In order to sort things, you need "things" to sort. Therefore you must group together all three numbers in a single entity, and then sort those entities. I suggest you use a Task class, and let it handle things like generating a unique task number. Avoid global variables.
Here is a minimal reproduction (based on your code) of just taking your three numbers in a tuple, combining them with the builtin "zip" and sorting that:
from random import randint
def generateData():
eventList = []
taskList = []
dayList = []
for _ in range(10):
randomEvent = randint(1, 5)
randomTask = randint(10, 30)
randomDay = randint(1, 9)
eventList.append(randomEvent)
taskList.append(randomTask)
dayList.append(randomDay)
return sorted(zip(eventList, taskList, dayList))
for task in generateData():
print(task)
Also note that python convention for variable names is a little different, but I left that alone and used your names.
Trying to write a program that generates random pw and stores that information in a variable that can be used to populate a mysql database.
I am able to generate the random password but am struggling to figure out how to store that information in a variable.
Here is the password generate code:
import random
from random import randint
import string
letters = (list(string.hexdigits + '!##$%^&*_'))
word = []
length = randint(8, 16)
for i in range(1, length):
char = random.choice(letters)
word.append(char)
for x in range(len(word)):
print(word[x], end = '')
It prints out the randomly generated password nicely, but what I want is to store that in a variable that can be used later. So far, nothing I have tried has worked.
Do you have any hints about how to accomplish this?
First, I am assuming you need to generate a password of length length, so in this case, you are not using correctly the range function. It can be fixed simply by changing range(1, length) to range(length).
As you have stated, the password is generated correctly in the list word, so now you just have to join the elements of this list, and store the result in a variable, let's call it generated_password:
generated_password = ''.join(word)
Alternatively, you can also simplify your code using the following:
generated_password = ''.join(random.choice(letters) for _ in range(length))
Rudimentary Python/ArcPy skills at work here, not sure where I'm going wrong.
Trying to do a simple random selection of 10 features from a layer to be indicated by the placement of a "1" in another attribute set aside for this purpose. Basic concept is is to use random.sample() to generate a random list of 10 FID's, and then check to see if each FID is in the list. NewID is an attribute containing FID's values. This is what I have in the code block:
import random
def randSelTen():
featurecount = arcpy.GetCount_management("layer_name")
linecount = int(str(featurecount))
lst_oids = range(0, linecount)
rand_lines = random.sample(lst_oids, 10)
if !NewID! in rand_lines:
return 1
else:
return 0
I keep getting a syntax error on the conditional containing !NewID!, and no matter what I do I can't fix it. If I replace !NewID! with an integer, the script runs, but of course the output is bad. Any help is appreciated... thanks!
If you are putting this code in the "Codeblock" of the field calculator then the reason you are getting a syntax error is because you can not access fields like that from the codeblock. You must pass in the field as an argument to the function. So you would have to do this:
# -----Codeblock---------
import random
def randSelTen(NewID):
featurecount = arcpy.GetCount_management("layer_name")
linecount = int(str(featurecount))
lst_oids = range(0, linecount)
rand_lines = random.sample(lst_oids, 10)
if NewID in rand_lines:
return 1
else:
return 0
# ----- Expression (goes in bottom text box of the field calculator if using GUI) -----
randSelTen(!NewID!)
I need to randomly pick an integer between two integers but that integer can't be in a list.
This is how I am doing it:
bannedReturningCustomersIndex = []
index = next(iter(set(range(0, 999)) - set(bannedReturningCustomersIndex)))
#some code..
bannedReturningCustomersIndex.append(index)
The problem is that I'm not pickig the integer randomly, I'm picking them 1 by 1 from the beginning...
Use random.choice after converting to a list:
import random
bannedReturningCustomersIndex = []
valid_indexes = list(set(range(0, 999)) - set(bannedReturningCustomersIndex))
bannedReturningCustomersIndex.append(random.choice(valid_indexes))
Even though the previous answer is correct, I'd like to propose the following approch, which is more readable, flexible and separates the logic from your main code.
import random
def iterRandNonBannedCustomers(banned_idx, c_idx=range(0, 999)):
c_idx = list(c_idx)
random.shuffle(c_idx)
return filter(lambda i: i not in banned_idx, c_idx)
The function returns an iterator over all non-banned customers. Use it, for example, like this:
for customer in iterRandNonBannedCustomers(bannedReturningCustomersIndex):
# do stuff
When using this following code:
import random
sticks = 100
randomstep = random.randint(1, 6)
expertmarbles = random.randrange(1, sticks, 2**randomstep)
the output is producing everything excluding the step, so for example i would like this to output a random from these numbers: 2,4,8,16,32,64. However it will output everything but these numbers. Can anyone offer any advice, the reason i'm using variables here is because the amount of sticks will decrease.
Instead of using random.randrange you could use random.choice (docs):
import random
min_power = 1
max_power = 6
print(random.choice([2**i for i in range(min_power, max_power + 1)]))
You can try this
def myRand(pow_min,pow_max):
return 2**random.randint(pow_min,pow_max)
I would suggest you to use this instead of random.choice, which requires you to generate a list, which is unnecessary.