简体   繁体   中英

What is the most efficient way to see whether one item of a list is the sum of two other items in the list?

The script is supposed to take in three whole numbers from the user(who will input the numbers) and

  1. determine whether one of them is divisible by ten.
  2. determine whether two of the numbers can add up to the remaining number.

I believe the first one is done, but the second one puzzled me for a bit. first I did "trial and error" which worked but took up too many lines for my taste, then I tried this:

num_list = [num_1, num_2, num_3]
for i in num_list:
    a = num_list.index(i)
    if i % 10 == 0:
        is_div_by_10 = True

    if i == num_list[a-1] + num_list[a-2]:
        addsUpToNumber = True

sure my phrasing isn't great, but I cant find a way to use lesser lines of code to get the same result.

Without changing too much, I think you were pretty close. I'd split it up into two separate loops though:

is_divisible = False
is_summable = False

num_list = [1, 2, 3]

for num in num_list:
    if num % 10 == 0:
        is_divisible = True
        break # we don't need to check the other numbers.

for i, num in enumerate(num_list):
    if num == num_list[i-1] + num_list[i-2]:
        is_summable = True
        break # we don't need to check the other numbers.

Alternatively:

is_divisible = any(num % 10 == 0 for num in num_list)
is_summable = any(num == num_list[i-1] + num_list[i-2] for i, num in enumerate(num_list))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM