如何解决使用迭代查找python中的最小k
我是编程的新手,我正在尝试迭代。
输入一个正整数:100
19
是最小的n,使得1+3+5+7+...+n >= 100
因此,从插入的整数开始,以2为步长,从1开始求和,直到总和等于插入的整数。
我收到一条错误消息
while r <= q:
TypeError: '<=' not supported between instances of 'range' and 'int'
我不确定在不使用范围和整数的情况下如何执行此操作。 有更好的方法吗?
到目前为止,我一直在下面的代码中进行尝试,但实际上是:我试图以2的步长创建变量和s,范围从0到q,然后s小于或等于q继续通过n求和。我输入了r尝试解决我遇到的错误,但是它仍然给出相同的错误。
也许我在想这是错误的方法,对您的帮助将不胜感激。 如果我提供了足够的信息,则表示歉意。让我知道,我将更新问题。
n = 0
q = int(input("enter a number"))
s = range(1,q,2)
r = s
while r <= q:
n= n+1
s= s+n
print("smallest N is",n)
答案
q = int(input("enter a number "))
s=[1] #start from 1
while sum(s) < q: #check if sum of s is less than input
s.append(s[-1]+2) #s[-1] will get the last element of list and +2 will ensure odd numbers are inserted in list
print("smallest N is",s[-1]) #get the last element in the list
完美运行 感谢大家的所有回答,非常感谢。 我只是好奇。如果我有
Enter a positive integer: 25
8 is the largest k such that 0+2+4+6+...+k < 25
应该得到8但得到10 `
q = int(input("enter a number "))
s=[0] #start from 0
while sum(s) < q:
s.append(s[-1]+2)
print("smallest N is",s[-1])
`
解决方法
这是一个简单的例子。
q = int(input("enter a number "))
s=[1] #start from 1
while sum(s) < q: #check if sum of s is less than input
s.append(s[-1]+2) #s[-1] will get the last element of list and +2 will ensure odd numbers are inserted in list
print("smallest N is",s[-1]) #get the last element in the list
,
我提出了这种解决方案:
q = int(input("enter a number"))
s = 0
r = iter(range(1,q,2))
while not s >= q:
n = next(r)
s += n
print("smallest N is",n)
它会在以下几点上修改您的版本:
- 我使用
s
作为累积金额,并用0
初始化 - 我将
r
设为迭代器,当我在其上运行next()
时会给我下一个值 - 我修改了
while
循环的条件,直到最终总和大于或等于用户输入的数字s
为止,直到总和q
为止。 - 在循环中,我检索范围迭代器的下一个元素,将其保存到
n
并将其添加到总和s
中。因此,我记得在最终总和s
大于或等于q
之前添加的最后一项
range
功能非常强大,但是您使用的方式不正确(这里确实没有必要)。
positive_integer = int(input('Enter a positive integer: '))
assert positive_integer >= 1
n = 1
sum = 1
while sum < positive_integer:
n += 2
sum += n
print('Smallest n is ',n)
,
您的代码出错,因为无法确定整数是否等于或小于范围。例如,我无法确定5是否小于,等于或大于60到110之间的数字。这不是数学的工作原理。但是,您可以确定该数字是小于,等于还是大于该范围内的最小数字。我建议您为此更改代码:
while r <= min(1,2):
n += 1
s += n
print("Smallest N is " + n)
,
q = int(input("enter a number"))
sum = 0;
n=0;
for i in range(1,2):
sum = sum+i
if(sum >= q):
n=i
break
print("smallest N is",n)
可以做到
,一个示例可以使您更容易理解: 假设q = 5 然后s = range(1,5,2)(在s上循环将生成1,3) 因此,s不是1的特定数字,而是“多个”数字。设置r = s表示r是多个数字。检查r
应该这样做。我尝试对它进行一些编码,以便解释,而又不做太多改动。
q = int(input("enter a number"))
r = range(1,2)
s = 0
n = 0
for i in r:
n = n + 1
s = s + i
if s >= q:
break
print("smallest N is",i)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。