决定帮助我的好友做一个实验室,这是我第一次这样做所以请不要取笑我的代码哈哈。我必须得到要添加到数组中的数字“num”,然后是总数。然后我想从数组的大小中添加用户定义的数字。然后,如果这些数字中的任何一个加起来等于总数,则将它们打印出来,否则打印 sorry。不明白为什么它不起作用:(
额外编辑:问题是,我的脚本不显示加起来总值的数字,只显示 print('sorry')
编辑:我在此之前学习过 java 和 C,无法弄清楚 foor 循环或如何实例化变量类型。
num = int(input('Please enter the amount of numbers you wish to use: '))
total = int(input('Please the total wild card number: '))
hasValue = int(0)
ar = []
i = int(0)
j = int(0)
k = int(0)
l = int(0)
m = int(0)
while (i < num):
j = i + 1
inNum = input('Please enter number %d:' %j)
ar.append(inNum)
i = i + 1
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
if (hasValue == 0):
print('sorry, there no such pair of values')
请您参考如下方法:
据我所知,您当前的脚本正在寻找两个后继 数字,其中总和等于total,但应该搜索数组中的任何对强>,对吧?所以如果我们有
ar = [1, 2, 3]
和
total = 5
程序应该显示2, 3 对。但是对于 total=4,它不会找到 1+3。
以下是一些一般性建议:
print调用出错,其中打印了对(string 应该在 str+int 连接中排在第一位)。使用格式print('%d, %d'.format(ar[k], ar[k])或将结果打印为元组
打印(ar[k], ar[l])使用
for k in range(num)而不是whilehasValue最好是 bool 值
好吧,这是我的解决方案(python2.7)
num = int(input("Array size: "))
sum = int(input("Search for: "))
a = []
found = False
# Fill array
for i in range(num):
a.append(int(input("Enter number #{}: ".format(i+1))))
# More effective algorithm - does not check same numbers twice
for i in range(num):
for j in range(i+1, num):
if a[i] + a[j] == sum:
print "{}, {}".format(a[i], a[j])
found = True
if not found:
print "Sorry..."
