Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Randomize in tables
#1
Hello!
I am wondering whether there is an opportunity for choosing random names with some conditions. I read about diffierent random functions from random package, but they choose only one number randomly. I also thought about function, but did not come up with idea how to write it properly.
I have a table with many columns (~15) and I need to choose some random names (no exact number) which total sum is less than or equal 500. Hence, here I need to get two names AQ2 and COR and then I will extract other information from the table.

name sum city
AQ2 400 N
L3K 50 L
COR 100 Q
… … …

Could you, please, advise me how to perform it?

Thank you in advance!
Sincerely,
Anastasia
Reply
#2
Try random.choice() or random.choices()

Maybe read up on weights=, I don't understand it! k=5 gives you 5 results

import random

mylist = ["apple", "banana", "mango", "cherry", "pear", "raspberry"]
print(random.choices(mylist, weights = None, k = 5))
Reply
#3
Thank you!
But how to incorporate the restriction of sum? I do not know the number of names to choose (k's). I only know that the sum of these k's must be less than or equal to some value X.

Thanks to your advice I tried to choose random names by loop "while". The code stops when the total sum is less than value X. In the function it takes one name randomly by random.choice and then remembers the name and the sum of this name. However, there is a problem which I do not know how to get rid of. That is replacement. By doing so radom.choice may take a name that has been already in the list. I am thinking of decreasing the initial table by one value each time. What do you think?

Thank you!
Reply
#4
I would make combinations that match the requirements and randomly choose from those.
import random
from itertools import combinations

all_choices = {key: random.randint(1, 5) for key in "ABCDEFG"}


def reduce(choices, count=1, total=float("inf")):
    return [
        combo
        for combo in combinations(choices.items(), count)
        if sum(item[1] for item in combo) <= total
    ]


# Get all combination of 5 choices who's sum <= 15
matching_choices = reduce(all_choices, 5, 15)
if matching_choices:
    print(
        f"{random.choice(matching_choices)} from {len(matching_choices)} matching combinations"
    )
else:
    print("No combination meets the requirements")
Reply
#5
Are you starting with an Excel file? If so, you could do it like this:

import openpyxl
import random
path2XL = '/home/pedro/myPython/openpyxl/random_data.xlsx'

wb = openpyxl.load_workbook(path2XL)
ws = wb.active
sheets = wb.sheetnames

# need some names and cities to choose from
names = ['Jack', 'Jill', 'Jane', 'John', 'Jennifer', 'Joseph', 'Jemma', 'Jesus']
cities = ['泰州', '上海', '杭州', '北京', '南京', '兰州', '昆明', '广州', '西安']
# assume row 1 contains column headers, so start in row 2
# this will put random values in the first 3 columns
# you could loop through the columns too
# maxCol = wb[sheet].max_column
for sheet in sheets:
    maxRow = wb[sheet].max_row
    # add 1 to maxRow or you won't get the last row
    for rowNum in range(2, ws.max_row + 1):        
        wb[sheet].cell(row=rowNum, column=1).value=random.choice(names)
        wb[sheet].cell(row=rowNum, column=2).value=random.randint(1, 500)
        wb[sheet].cell(row=rowNum, column=3).value=random.choice(cities)

savename = 'random_data2.xlsx'
savepath = '/home/pedro/myPython/openpyxl/'
wb.save(savepath + savename)
print('All done!')
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020