如何解决函数必须返回一个由大于或等于的最小偶数组成的列表,按升序排序
- 被命名为偶数
- 接受 2 个整数参数,start 和 n。
- 以升序返回大于或等于 start 的 n 个最小偶数的列表。
该函数的实现将通过提供的代码存根在多个输入文件上进行测试。每个输入文件都包含函数调用的参数。将使用这些参数调用该函数,并通过提供的代码将其执行结果打印到标准输出。
约束
• 1
自定义测试的输入格式
在第一行也是唯一的一行,有两个空格分隔的整数,start 和 n。
示例案例 0
样本输入
标准输入功能 2 4 开始 = 2,n = 4
样本输出
2 4 6 8
说明该函数必须返回一个由大于或等于 2 的 4 个最小偶数组成的列表,按升序排序:2、4、6 和 8。
到目前为止,以下是我的代码,但它只打印列表范围内的偶数,而不是列表中提到的长度:-
def even(start,n):
count = []
for i in range(start,n):
if 1 <= start and n <= 100:
if i % 2 == 0:
count.append(i)
return [count]
start = int(input("Enter the number where the even should start from: "))
n = int(input("Enter the value of length you want to show the even numbers of: "))
print(even(start,n))
解决方法
你的代码大多是错误的。这样做:
def even(start,n):
if start % 2:
start += 1 # If odd,start from the next even
return [x for x in range(start,start+2*n+1,2)]
,
def even(start,start + 2 * n,2)]
start = int(input("Enter the number where the even should start from: "))
n = int(input("Enter the value of length you want to show the even numbers of: "))
print(even(start,n))
,
我相信您在范围声明中遇到了麻烦。
for i in range(start,n):
这可能可以重写为range(start,start + n)。对您的循环逻辑进行一些更改,此推理将帮助您实现目标。
解决此问题的另一种方法可能是确定起始值是否为偶数,然后向其添加偶数。在下面的解决方案中,length 的含义更清楚。
def even(start,n):
count = []
# Check if start is even
if start % 2 != 0:
start = start + 1
# A set of even numbers can be thought of the set of all numbers multiplied by 2
for i in range(0,n):
count.append(start + i*2)
return count
start = int(input("Enter the number where the even should start from: "))
n = int(input("Enter the value of length you want to show the even numbers of: "))
print(even(start,n))
,
你的代码几乎没问题。您只需要在这部分进行一些更改。
for i in range(start,start+2*n):
if i % 2 == 0:
count.append(i)
return count
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。