python将值分配到不同的列表(算法)

2024-09-29 19:30:23 发布

您现在位置:Python中文网/ 问答频道 /正文

描述

我在我的大学里有一个项目学习的问题。下面是一个简单的例子:

python - distribute values to different lists

  • 有特定数量项目的位置(来源-左侧)。你知道吗
  • 这些源连接到某些(并非所有)目标位置(右侧)。你知道吗
  • 目的地有一个他们应该接收的最小数量
  • 尤其是“绿色”的(Dest. X),因为它是优先的。如果来源的项目太少,则完成此目的地的最小数量比其他目的地的最小数量更重要。你知道吗
  • 一些目的地有一个最大数量的项目,他们可以采取。你知道吗

问题/方法

我已经开始用python脚本来处理这个问题。它用随机数量的项创建sourcesdestinations。但是我不知道如何分配所有的项目,包括mininum amountsmaximum_amounts、优先级排序,当然还有一个事实,不是所有的源都连接到所有的目的地。你知道吗

欢迎使用任何方法,最好使用几行代码:)

提前谢谢


Tags: 项目方法脚本目标数量来源例子大学
1条回答
网友
1楼 · 发布于 2024-09-29 19:30:23

我的方法是:

import random
nums = [100]+[200]+[500]
#used to check if the vars have been chekd b4
xc = 0
yc = 0
zc = 0

#define Sources:
a = random.choice(nums) #I decided to define them at random
b = random.choice(nums)
c = random.choice(nums)
d = random.choice(nums)

#Define Destinations:
x = 0 #min: 500
y = 0 #min: 100 #max: 200
z = 0 #min: 300

#prioritize:
pri = 0
if a+b+c < 500:
    pri = 1

#fill x:
if pri == 0:
    if a >= 500 and xc == 0:
        x += a
        a -= a
        xc = 1
    if b >= 500 and xc == 0:
        x += b
        b -= b
        xc = 1
    if c >= 500 and xc == 0:
        x += c
        c -= c
        xc = 1
if pri == 1:
    x += a+b+c
    a -= a
    b -= b
    c -= c
#we didnt test for d bcus its not cond

#fill y:
if b >= 100 and b <= 200 and yc == 0:
    y += b
    b -= b
    yc = 1
if c >= 100 and b <= 200 and yc == 0:
    y += c
    c -= c
    yc = 1
if d >= 100 and b <= 200 and yc == 0:
    y += d
    d -= d
    yc = 1

#fill z:
if a >= 300 and zc == 0:
    z += a
    a -= a
    zc = 1
if c >= 300 and zc == 0:
    z += c
    c -= c
    zc = 1
if d >= 300 and zc == 0:
    z += d
    d -= d
    zc = 1

#test if it is filled:
print("X: "+"{}".format(x)+"/500+")
print("Y: "+"{}".format(y)+"/100_200")
print("Z: "+"{}".format(z)+"/300+")
#X:
if x >= 500:
    print("X filled correctly!")
if x < 500:
    print("X not filled!")
#Y:
if y >= 100 and y <= 200:
    print("Y filled correctly!")
if y < 100:
    print("Y not filled!")
if y > 200:
    print("Y over-filled!")
#Z:
if z >= 300:
    print("Z filled correctly!")
if z < 300:
    print("Z not filled!")

input()#waits for you to end it manually

有时X不会被填充,尽管一个值是500,因为d没有连接到X(有时d可以是500)

对不起,如果我错了!我的数学不太好,我花了一段时间才(希望)明白OP想要什么。 希望我至少在某些方面有所帮助。(必须使用大量的代数)

相关问题 更多 >

    热门问题