我试图将“ x”添加到间隔“ a”和“ b”之间的列表“ arr”中。该列表已更新了'm'次。(即)我们在间隔'a'和'b'之间将'x'添加到了'm'次。仅设法在'arr'中更新了'x'值在'a'和'b'处而不是在间隔之间。请帮忙!
def main():
arr=[]
n=int(input())
m=int(input())
for i in range(n):
arr.append(0)
for i in range(m):
a=int(input())
b=int(input())
x=int(input())
for j,c in range(len(arr)):
if j==a-1 :
arr[a-1]=x+arr[a-1]
if j==b-1:
arr[b-1]=x+arr[b-1]
print(arr)
if __name__ == '__main__':
main()
答案 0 :(得分:0)
我不清楚这个问题,但是我认为您要说的是:
我忽略了'm'。
arr = []
array_length = int(input('Length of initial array >'))
arr = [0]*array_length # Create the array
keep_running = True # Replacing the use of 'm' - less parameters for the user!
while keep_running:
x = int(input('Number to add >'))
param_index_start = int(input('Start at index >')) #formerly 'a'
# Lets check that the start index is valid
if param_index_start > len(arr):
print("Start index must be less than initial array length ({})".format(len(arr)))
continue
param_index_stop = int(input('Finish at index >')) #formerly 'b'
arr_length = len(arr)
# Lets make sure we are not trying to access indexes which do not exist
stop_index = min(arr_length, param_index_stop)
start_index = min(arr_length, param_index_start)
print("Adding {} to indexes {} to {}".format(x, start_index, stop_index))
# Do the addition
for index in range(start_index, stop_index):
arr[index] += x
print("Current array: ", arr)
# Allow the user an opportunity to exit
continue = input("Continue adding? Y/N >")
if continue == "N":
keep_running = False
这是一些示例输出(压缩为空格)
Length of initial array > 10
Number to add > 1
Start at index > 5
Finish at index > 10
Adding 1 to indexes 5 to 10
Current array: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
Continue adding? Y/N > Y
Number to add > 3
Start at index > 4
Finish at index > 7
Adding 3 to indexes 4 to 7
Current array: [0, 0, 0, 0, 3, 4, 4, 1, 1, 1]
Continue adding? Y/N > Y
Number to add > 1
Start at index > 0
Finish at index > 20
Adding 1 to indexes 0 to 10
Current array: [1, 1, 1, 1, 4, 5, 5, 2, 2, 2]
Continue adding? Y/N > N
[1, 1, 1, 1, 4, 5, 5, 2, 2, 2]
您可以找到repl示例here
我可能误解了你的问题。