[英]how get list of all the possible combinations of 4 digit numbers whose individual digit sum is 13 and last digit is 5 in that number
[英]How to find the sum of first and last digit in a list
我希望我的程序允許用戶輸入兩個整數列表,計算每個列表中第一個和最后一個整數的總和並打印更大的總和。 目前它只輸出list2
兩次。
list1 = []
list2 = []
n1 = [int(n) for n in input("List 1: ").split()]
list1.append(n1)
n2 = [int(n) for n in input("List 2: ").split()]
list2.append(n2)
s1 = 0
s2 = 0
s1 = list1[0] + list1[len(list1) - 1]
s2 = list2[0] + list2[len(list2) - 1]
if s1 > s2:
print("Output: ", s1)
elif s1 < s2:
print("Output: ", s2)
else:
print("Output: Same")
這就是我得到的。 我應該得到 12 作為 Output。
List 1: 1 2 3 4 5
List 2: 5 6 7
Output: [5, 6, 7, 5, 6, 7]
我究竟做錯了什么?
append
將一個元素添加到列表中,而不是合並 2 個列表,因此list1
和list2
的值分別為: [[1,2,3,4,5]]
和[[5,6,7]]
,只需使用:
list1 = [int(n) for n in input("List 1: ").split()]
list2 = [int(n) for n in input("List 2: ").split()]
或者,您可以用extend
替換您對append
的調用,這會將提供的列表連接在一起。
您犯了一個錯誤: n1
已經是一個列表,因此您的list1
變為[[1,2,3,4,5]]
- 它有 1 個元素,即 5 個元素的列表。 與n2
和list2
相同。
我重寫了你的代碼,你也可以使用lst[-1]
而不是lst[len(lst)-1]
list1 = [int(n) for n in input("List 1: ").split()]
list2 = [int(n) for n in input("List 2: ").split()]
s1 = list1[0] + list1[-1]
s2 = list2[0] + list2[-1]
if s1 > s2:
print("Output: ", s1)
elif s1 < s2:
print("Output: ", s2)
else:
print("Output: Same")
# Take inputs from users
list1 = [int(n) for n in input("List 1: ").split()]
list2 = [int(n) for n in input("List 2: ").split()]
# SUM of first and last
sum1 = list1[0] + list1[-1]
sum2 = list2[0] + list2[-1]
# Checking
if sum1 > sum2:
print("Output: ", sum1)
elif sum1 < sum2:
print("Output: ", sum2)
else:
print("Output: Same")
"""
OUTPUT:
-------------
List 1: 1 2 3
List 2: 4 5 6
Output: 10
"""
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.