How to quickly find the maximum value by adding the values ​of items in python

I want to optimize this code to make it run faster when given a variety of data. I would appreciate it if you could also include an explanation of the optimization method.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
def parse_input():
# Read the number of parts from the first line
N = int(input().strip())
parts = {'Body': [], 'Handle': [], 'Wheel': [], 'Engine': [], 'Booster': []}
part_performance = {}
for _ in range(N):
category, name, performance = input().strip().split()
performance = int(performance)
parts[category].append((name, performance))
part_performance[name] = performance
# Read the number of synergies from the second line
M = int(input().strip())
synergies = {}
for _ in range(M):
part_a, part_b, synergy = input().strip().split()
synergy = int(synergy)
synergies[(part_a, part_b)] = synergy
synergies[(part_b, part_a)] = synergy
# Read the target performance S from the third line
S = int(input().strip())
return parts, part_performance, synergies, S
def find_best_combination(parts, part_performance, synergies, S):
from itertools import product
best_combination = None
closest_performance = float('inf')
for body, handle, wheel, engine, booster in product(parts['Body'], parts['Handle'], parts['Wheel'], parts['Engine'], parts['Booster']):
combination = [body, handle, wheel, engine, booster]
total_performance = sum(part[1] for part in combination)
# Calculate synergy effects
synergy_bonus = 0
for i in range(5):
for j in range(i + 1, 5):
part1 = combination[i][0]
part2 = combination[j][0]
if (part1, part2) in synergies:
synergy_bonus += synergies[(part1, part2)]
total_performance += synergy_bonus
if abs(total_performance - S) < abs(closest_performance - S):
closest_performance = total_performance
best_combination = combination
return best_combination
def main():
parts, part_performance, synergies, S = parse_input()
best_combination = find_best_combination(parts, part_performance, synergies, S)
if best_combination:
for part in best_combination:
print(part[0])
if __name__ == "__main__":
main()
</code>
<code> def parse_input(): # Read the number of parts from the first line N = int(input().strip()) parts = {'Body': [], 'Handle': [], 'Wheel': [], 'Engine': [], 'Booster': []} part_performance = {} for _ in range(N): category, name, performance = input().strip().split() performance = int(performance) parts[category].append((name, performance)) part_performance[name] = performance # Read the number of synergies from the second line M = int(input().strip()) synergies = {} for _ in range(M): part_a, part_b, synergy = input().strip().split() synergy = int(synergy) synergies[(part_a, part_b)] = synergy synergies[(part_b, part_a)] = synergy # Read the target performance S from the third line S = int(input().strip()) return parts, part_performance, synergies, S def find_best_combination(parts, part_performance, synergies, S): from itertools import product best_combination = None closest_performance = float('inf') for body, handle, wheel, engine, booster in product(parts['Body'], parts['Handle'], parts['Wheel'], parts['Engine'], parts['Booster']): combination = [body, handle, wheel, engine, booster] total_performance = sum(part[1] for part in combination) # Calculate synergy effects synergy_bonus = 0 for i in range(5): for j in range(i + 1, 5): part1 = combination[i][0] part2 = combination[j][0] if (part1, part2) in synergies: synergy_bonus += synergies[(part1, part2)] total_performance += synergy_bonus if abs(total_performance - S) < abs(closest_performance - S): closest_performance = total_performance best_combination = combination return best_combination def main(): parts, part_performance, synergies, S = parse_input() best_combination = find_best_combination(parts, part_performance, synergies, S) if best_combination: for part in best_combination: print(part[0]) if __name__ == "__main__": main() </code>

def parse_input():

    # Read the number of parts from the first line

    N = int(input().strip())

    

    parts = {'Body': [], 'Handle': [], 'Wheel': [], 'Engine': [], 'Booster': []}

    part_performance = {}

    

    for _ in range(N):

        category, name, performance = input().strip().split()

        performance = int(performance)

        parts[category].append((name, performance))

        part_performance[name] = performance

    

    # Read the number of synergies from the second line

    M = int(input().strip())

    

    synergies = {}

    for _ in range(M):

        part_a, part_b, synergy = input().strip().split()

        synergy = int(synergy)

        synergies[(part_a, part_b)] = synergy

        synergies[(part_b, part_a)] = synergy

    

    # Read the target performance S from the third line

    S = int(input().strip())

    

    return parts, part_performance, synergies, S



def find_best_combination(parts, part_performance, synergies, S):

    from itertools import product



    best_combination = None

    closest_performance = float('inf')

    

    for body, handle, wheel, engine, booster in product(parts['Body'], parts['Handle'], parts['Wheel'], parts['Engine'], parts['Booster']):

        combination = [body, handle, wheel, engine, booster]

        total_performance = sum(part[1] for part in combination)

        

        # Calculate synergy effects

        synergy_bonus = 0

        for i in range(5):

            for j in range(i + 1, 5):

                part1 = combination[i][0]

                part2 = combination[j][0]

                if (part1, part2) in synergies:

                    synergy_bonus += synergies[(part1, part2)]

        

        total_performance += synergy_bonus

        

        if abs(total_performance - S) < abs(closest_performance - S):

            closest_performance = total_performance

            best_combination = combination



    return best_combination



def main():

    parts, part_performance, synergies, S = parse_input()

    best_combination = find_best_combination(parts, part_performance, synergies, S)

    

    if best_combination:

        for part in best_combination:

            print(part[0])



if __name__ == "__main__":

    main()



This is an input example.

9

Body red 50

Body purple 50

Handle redsoft 30

Handle redhard 40

Handle purplesoft 30

Wheel purplehard 50

Engine redstrong 20

Engine purplecalm 10

Booster redcalm 10

5

red redsoft 20

red redhard 20

purplesoft purplehard 100

redstrong red 10

redstrong redcalm 50

169

Processing speed is not fast enough when input increases.

New contributor

scenery tv is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật