如何对以列表形式呈现的不同大小的数字组进行求和,并找到最高的总和。

huangapple go评论79阅读模式
英文:

How can I sum of groups of varying sizes of numbers presented as a list and find the highest sum

问题

如果有人可以帮助我解决这个编程难题(2022 年的第 1 天 - 进展不太顺利!):你需要将各种大小的组中的所有数字相加(100、2000、3000 是第 1 组,4000 是第 2 组),以换行符分隔。然后,你需要将每个组的数字相加并找到最大值。

1000
2000
3000

4000

5000
6000

7000
8000
9000

10000

我已经尝试用组号替换列表中的每个换行符,但仍然没有帮助,我猜想可能需要将其转化为数据框,但不确定如何处理不同长度的组,非常感谢任何帮助!

英文:

if anyone could help me out with this advent of code (Day 1 2022 - haven't got very far!): You have to add up all the numbers of each group of varying sizes (100,2000,3000 is group 1, 4000 is group 2), separated by a line break. You then have to add up each group and find the highest.

1000
2000
3000

4000

5000
6000

7000
8000
9000

10000

I've tried replacing each line break in the list with the group number, but still doesn't help, presume it needs to be turned into a dataframe but unsure with varying lengths of group how to do this, any help would be much appreciated!

答案1

得分: 1

group_sums = []
for line in x.split('\n'):
current = [int(el) for el in line.split(' ')]
group_sums.append(sum(current))

group_sums
Out[4]: [6000, 4000, 11000, 24000, 10000]

max(group_sums)
Out[5]: 24000

英文:

No need for pandas.

x = '''1000 2000 3000
4000
5000 6000
7000 8000 9000
10000'''

group_sums = []
for line in x.split('\n'):
    current = [int(el) for el in line.split(' ')]
    group_sums.append(sum(current))
    
group_sums
Out[4]: [6000, 4000, 11000, 24000, 10000]

max(group_sums)
Out[5]: 24000

答案2

得分: 1

看完原问题后,数字组是由两个换行符分隔的。由于您可能想要自己解决问题,我只会指出正确的方向。考虑使用.split(c)方法,该方法将给定的字符串分解为一个字符串列表,并在所有出现c的地方断开它。您可以使用int(str_here)将字符串强制转换为整数。

为了完整起见,以下是一个简单的Python解决方案:

groups = open("input.txt").read().split("\n\n")
groups = [group.split("\n") for group in groups]
groups = [[int(item) for item in group] for group in groups]
groups = [sum(group) for group in groups]
print(max(groups))

当然,这不是最快的解决方案,而且Python本身速度较慢,但我希望它容易理解。列表推导式(表达式如[thing for thing in group_of_things])是Python中的强大工具。

英文:

Having taken a look at the original problem question, the groups of numbers are separated by two newline characters. Since you would probably like to solve the problem yourself, I will just point you in the right direction. Consider using the .split(c) method, which decomposes a given string into a list of strings breaking it at all occurences of c. And you can typecast strings to integers by using int(str_here).

A simple solution in python for the sake of completeness:

groups = open("input.txt").read().split("\n\n")
groups = [group.split("\n") for group in groups]
groups = [[int(item) for item in group] for group in groups]
groups = [sum(group) for group in groups]
print(max(groups))

Of course this is not the fastest solution, and python itself is very slow, but I hope it is easy to understand. List comprehensions (expressions such as[thing for thing in group_of_things]) are a powerful tool in python.

答案3

得分: 1

以下是一个示例解决方案:

input_data = '''1000 2000 3000
4000
5000 6000
7000 8000 9000
10000'''

groups = input_data.split('\n')  # 根据换行符将输入拆分为组

max_sum = 0
max_sum_line = -1

for i, group in enumerate(groups):
    numbers = group.split()  # 将组拆分为单独的数字
    numbers = [int(num) for num in numbers]  # 将数字从字符串转换为整数
    group_sum = sum(numbers)  # 计算每组的总和
    if group_sum > max_sum:
        max_sum = group_sum
        max_sum_line = i + 1  # 行号从1开始,而不是从0开始

print("最大总和", max_sum)
print("具有最大总和的行号", max_sum_line)

输出结果是:

最大总和24000
具有最大总和的行号4
英文:

Here is a sample solution:

input_data = '''1000 2000 3000
4000
5000 6000
7000 8000 9000
10000'''

groups = input_data.split('\n')  # Split input into groups based on line breaks

max_sum = 0
max_sum_line = -1

for i, group in enumerate(groups):
    numbers = group.split()  # Split group into individual numbers
    numbers = [int(num) for num in numbers]  # Convert numbers from string to integer
    group_sum = sum(numbers)  # Calculate the sum of each group
    if group_sum > max_sum:
        max_sum = group_sum
        max_sum_line = i + 1  # Line numbers start from 1, not 0

print("Maximum sum:", max_sum)
print("Line number with the biggest sum:", max_sum_line)

output is:

Maximum sum: 24000
Line number with the biggest sum: 4

答案4

得分: 1

我不太强壮,可能还有改进的空间,但这是我所做的:

data = """1000 2000 3000
4000
5000 6000
7000 8000 9000
10000"""

groups = data.split("\n")

groups_sums = []

for i in groups:
    fragment = i.split(" ")
    somme = 0
    for i in fragment:
        somme += int(i)
    groups_sums.append(somme)

max_sum = max(groups_sums)
max_sum_index = groups_sums.index(max_sum)

print("具有最大总和的组,编号:", max_sum_index + 1, "值:", max_sum, "数据:", groups[max_sum_index])

请注意,这是您提供的Python代码的翻译。

英文:

I'm not very strong, there are probably improvements to be made, but here's what I did:

data = """1000 2000 3000
4000
5000 6000
7000 8000 9000
10000"""

groups = data.split("\n")

groups_sums = []

for i in groups:
    fragment = i.split(" ")
    somme = 0
    for i in fragment:
        somme += int(i)
    groups_sums.append(somme)

max_sum = max(groups_sums)
max_sum_index = groups_sums.index(max_sum)

print("Group with the max sum, number :",max_sum_index + 1,"value :",max_sum,"data :", groups[max_sum_index])

答案5

得分: 0

由于您有一个[dataframe]标签,假设输入是txt-csv文件,您可以使用:

tmp = pd.read_csv("file.txt", header=None, skip_blank_lines=False)[0]

grp = (tmp.shift().isnull() & tmp.notnull()).cumsum()

grp_sums = tmp.groupby(grp).sum().to_frame("values").rename_axis("group")

highest = grp_sums.loc[grp_sums.idxmax()] # `.iat[0, 0]` 返回一个标量

输出:

print(grp_sums)

        values
group         
1      6000.00
2      4000.00
3     11000.00
4     24000.00
5     10000.00

print(highest)

        values
group         
4     24000.00
英文:

Since you have a [tag:dataframe] tag and assuming the input is a txt-csv.. file, you can use :

tmp = pd.read_csv("file.txt", header=None, skip_blank_lines=False)[0]
​
grp = (tmp.shift().isnull() & tmp.notnull()).cumsum()
​
grp_sums = tmp.groupby(grp).sum().to_frame("values").rename_axis("group")
​
highest = grp_sums.loc[grp_sums.idxmax()] # `.iat[0, 0]` to return a scalar


Output :

print(grp_sums)
​
        values
group         
1      6000.00
2      4000.00
3     11000.00
4     24000.00
5     10000.00

print(highest)

        values
group         
4     24000.00

huangapple
  • 本文由 发表于 2023年5月28日 18:52:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76351106.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定