我遇到了无法解决python分组问题的问题

问题描述 投票:0回答:1

如何按照以下说明用Python语言编写代码:

  1. 将从用户处接收 Int 值。当用户输入值0时,值检索过程将完成。
  2. 输入的值将存储在数组中。
  3. 组必须有最小组数,每组元素之和小于70
  4. 组将打印在屏幕上。

我写了,但不起作用。代码有什么问题?我应该编辑哪部分代码?

aray = []
while True:
    a = int(input("Sayı gir:"))
    if a != 0:
        aray.append(a)
    else:
        break


x = 700

aray.sort(reverse=True)
aray2 = aray.copy()
array =[]

target = 700
groups = []
currentGroup = []
currentSum = 0

for number in fonk(x,aray,aray2):
    if currentSum + number <= target:
        currentGroup.append(number)
        currentSum += number
    else:
        groups.append(currentGroup)
        currentGroup = [number]
        currentSum = number

groups.append(currentGroup)

for group in groups:
    print("Group:")
    for num in group:
        print(num, end=" ")
    print()
    
def fonk(x,arr, aray2):
    count = 1
    min = 710
    for in1 in range(len(arr)):
        i = arr[in1]
        flag = False
        jj = 0
        for minfind in aray2:
            if minfind < min:
                min = minfind
        for j in aray2:
            if x >= j:
                flag = True
                jj = j
                aray2.remove(jj)
                break
        if not flag:
            continue
        if x >= jj:
            x -= jj
            array.append(jj)
            if x==0 or x<= min:
                x=700
                count+=1
            continue
        else: 
            x = 700
            count +=1
    
    return array

输入:

400
10
700
200
600
490
160
300
200
320

我的输出:

Group:
700
Group:
600
Group:
490 200
Group:
400 300
Group:
320 200 160
Group:
100

但是输出应该是:

700
600 100
490 200
400 300
320 200 160
python algorithm grouping
1个回答
0
投票

您在寻找这样的东西吗

  • 就像您已经想到的那样,您需要先对列表进行排序。
  • 然后,将每个数字添加到其适合的第一个组中,并在必要时创建新组。
from __future__ import annotations

MAX_SUM = 700

numbers: list[int] = []
while True:
    number = int(input("Number:"))
    if not number:
        break

    numbers.append(number)

numbers.sort(reverse=True)
groups: list[list[int]] = []
for number in numbers:
    for group in groups:
        if sum(group) + number <= MAX_SUM:
            group.append(number)
            break
    else:
        groups.append([number])

for group in groups:
    print(group)
© www.soinside.com 2019 - 2024. All rights reserved.