Python - 从列表中提取随机数.使用指定的长度和总和填充新列表 [英] Python - Pull random numbers from a list. Populate a new list with a specified length and sum

查看:83
本文介绍了Python - 从列表中提取随机数.使用指定的长度和总和填充新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,其中:

I am trying to create a function where:

  1. 输出列表由输入列表中的随机数生成
  2. 输出列表是指定长度并添加到指定总和

例如.我指定我想要一个长度为 4 并且加起来为 10 的列表.从输入列表中提取随机数,直到满足条件.

ex. I specify that I want a list that is 4 in length and adds up to 10. random numbers are pulled from the input list until the criteria is satisfied.

我觉得我尝试使用递归来解决这个问题都是错误的.任何帮助将不胜感激!!!

I feel like I am approaching this problem all wrong trying to use recursion. Any help will be greatly appreciated!!!

关于这个问题的更多背景......它将是一个随机敌人生成器.

for more context on this problem.... Its going to be a random enemy generator.

最终目标输入列表将来自一个名为 XP 的 CSV 列.(我打算使用熊猫模块).但是这个 CSV 将在一列中列出敌人的名字,在另一列中列出 XP,在另一列中列出生命值,等等.所以最终目标是能够指定敌人的总数以及这些敌人之间的 XP 总和应该是多少并使用适当的信息生成列表.例如.5 个敌人,总共 200 XP.结果可能是 -> Apprentice Wizard(50 xp)、Apprentice Wizard(50 xp)、Grung(50)、Xvart(25 xp)、Xvart(25 xp).输出列表实际上需要包含所选项目的所有行信息.如本例所示,在输出中进行复制是完全没问题的.这实际上在游戏的叙述中更有意义.

The end goal input list will be coming from a column in a CSV called XP. (I plan to use pandas module). But this CSV will have a list of enemy names in the one column, XP in another, Health in another, etc. So the end goal is to be able to specify the total number of enemies and what the sum XP should be between those enemies and have the list generate with the appropriate information. For ex. 5 enemies with a total of 200 XP between them. The result is maybe -> Apprentice Wizard(50 xp), Apprentice Wizard(50 xp), Grung(50), Xvart(25 xp), Xvart(25 xp). The output list will actually need to include all of the row information for the selected items. And it is totally fine to have duplicated in the output as seen in this example. That will actually make more sense in the narrative of the game that this is for.

csv --> https://docs.google.com/spreadsheets/d/1PjnN00bikJfY7mO3xt4nV5Ua1yOIsh8DycGqed6hWD8/edit?usp=sharing

import random
from random import *

lis = [1,2,3,4,5,6,7,8,9,10]

output = []

def query (total, numReturns, myList, counter):

    random_index = randrange(len(myList)-1)
    i = myList[random_index]
    h = myList[i]

    # if the problem hasn't been solved yet...
    if len(output) != numReturns and sum(output) != total:
        print(output)

        # if the length of the list is 0 (if we just started), then go ahead and add h to the output
        if len(output) == 0 and sum(output) + h != total:
            output.append(h)
            query (total, numReturns, myList, counter)


        #if the length of the output is greater than 0
        if len(output) > 0:

            # if the length plus 1 is less than or equal to the number numReturns
            if len(output) +1 <= numReturns:
                print(output)

                #if the sum of list plus h is greater than the total..then h is too big. We need to try another number
                if sum(output) + h > total:
                    # start counter

                    for i in myList:#  try all numbers in myList...
                        print(output)
                        print ("counter is ", counter, " and i is", i)
                        counter += 1
                        print(counter)

                        if sum(output) + i == total:
                            output.append(i)
                            counter = 0
                            break
                        if sum(output) + i != total:
                           pass
                        if counter == len(myList):
                            del(output[-1]) #delete last item in list
                            print(output)
                            counter = 0 # reset the counter
                    else:
                        pass

                #if the sum of list plus h is less than the total
                if sum(output) + h < total:
                    output.append(h) # add h to the list

        print(output)
        query (total, numReturns, myList, counter)


    if len(output) == numReturns and sum(output) == total:
        print(output, 'It worked')
    else:
        print ("it did not work")


query(10, 4, lis, 0)

推荐答案

我想最好先获得给定数组的所有 n 大小组合,这些组合添加到指定的数字,然后随机选择其中一个.随机选择并检查 sum 是否等于指定值,在悲观情况下,可以无限期持续.

I guess that it would be better to get first all n-size combinations of given array which adds to specified number, and then randomly select one of them. Random selecting and checking if sum is equal to specified value, in pessimistic scenario, can last indefinitely.

from itertools import combinations as comb
from random import randint

x = [1,1,2,4,3,1,5,2,6]

def query(arr, total, size):
  combs = [c for c in list(comb(arr, size)) if sum(c)==total]
  return combs[randint(0, len(combs))]

#example 4-item array with items from x, which adds to 10
print(query(x, 10, 4))


这篇关于Python - 从列表中提取随机数.使用指定的长度和总和填充新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆