Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

write a simple program in python about sum in list

I want to write a program to give some number for user then if sum of 3 number in list == 0 prit yes: part of my code:

import os
from typing import Mapping
from colorama import Fore , init
init()
os.system("cls" or "clear")
clear = lambda: os.system('cls')

# GIVE LIST NUMBER
listed = input(Fore.GREEN+"Please Enter A List Of Number: ")
# CONVERT INPUT(STR) TO LIST:
listed = list(map(int, listed.split(',')))
listed= list(map(int, listed))
#CHEACK SUM IN LIST == 0

I don't know how check my IF to Print yes or no.....

Example:

list = [3 , 2 , -2 , -5]

print YES as 3+2-5 = 0

question from:https://stackoverflow.com/questions/65873850/write-a-simple-program-in-python-about-sum-in-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I guess you want something like this:

import os
from typing import Mapping
from colorama import Fore , init
init()
os.system("cls" or "clear")
clear = lambda: os.system('cls')

# GIVE LIST NUMBER
listed = input(Fore.GREEN+"Please Enter A List Of Number: ")
# CONVERT INPUT(STR) TO LIST:
listed = list(map(int, listed.split(',')))
listed= list(map(int, listed))
#CHEACK SUM IN LIST == 0

if sum(listed) == 0:
    print("yes")

Updated (from your comment):

from itertools import combinations

list1 = [3, 2]
list2 = [3, 2, -2, -5]
list3 = [5, -5, 0]


def check_sum(list_of_numbers):
    if len(list_of_numbers) >= 3:
        subsets = list(combinations(list_of_numbers, 3))
        for each_subset in subsets:
            if sum(each_subset) == 0:
                return "Yes"
        return "No"
    else:
        return "No"


print(check_sum(list1))
print(check_sum(list2))
print(check_sum(list3))

Output:

No
Yes
Yes

Some credits to https://www.geeksforgeeks.org/python-program-to-get-all-subsets-of-given-size-of-a-set/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...