[英]Beginners python program
决定帮助我的伙伴做一个实验室,这是第一次这样做,所以请不要取笑我的代码,哈哈。 我必须得到一个数字“num”,表示要添加到数组中的数字,然后是总数。 然后我想从数组的大小中添加用户定义的数字。 然后,如果这些数字中的任何一个与总数相加,则将它们打印出来,否则打印抱歉。 不明白为什么它不起作用:(
额外编辑:问题是,我的脚本没有显示加起来的数字,只有打印('抱歉')
编辑:我在此 java 和 C 之前学习过,无法弄清楚 foo 循环或如何实例化变量类型。
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')
这是在python中执行for循环的方法:
for x in range(10):
# code for the for loop goes here
这相当于:
for (int x = 0; x < 10; x++) {
// code for the for loop goes here
}
...在 C++ 中
(注意没有初始化变量 'x'。当你执行 for 循环时,python 会自动初始化它。
这是我认为你希望做的:
def main():
num = int(input("Enter the amount of numbers: "))
total = int(input("Enter the total: "))
array = []
counter, elem = 0, 0
for user_numbers in range(num):
array.append(int(input("Please enter number: ")))
for each_element in array:
counter += each_element
elem += 1
if counter == total:
print(array[:elem])
break
if counter != total:
print("sorry...")
main()
据我所知,您当前的脚本正在寻找 sum 等于total
两个后续数字,但应该搜索array 中的任何对,对吗? 所以如果我们有
ar = [1, 2, 3]
和
total = 5
程序应显示2, 3
对。 但它不会为total=4
找到1+3
。
以下是一些一般性建议:
print
调用中有错误,其中print
对(字符串应该在 str+int 连接中排在第一位)。 使用格式
print('%d, %d'.format(ar[k], ar[k])
或将结果打印为元组
print(ar[k], ar[l])
for k in range(num)
而不是while
hasValue
最好是布尔值
好吧,这是我的解决方案(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..."
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
除了循环不是“pythonic”这一事实之外,您还需要在 k 循环中初始化 l = 0。
while (k < num):
l = 0
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
或者稍微多一点的python方式:
for num1 in ar:
for num2 in ar:
if num1+num2==total:
print(num1 +' , '+ num2) # not sure about this syntax. I am a python beginner myself!
hasValue = hasValue + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.