Python: List of Even Integers, implement a function that:
Implementation of the function will be tested by a provided code stub on several input files. Each input file contains parameters for the function call. The function will be called with those parameters, and the result of its execution will be printed to the standard output by the provided code.
Constraints
• 1 <= start, n <= 100
Input Format Format for Custom Testing
In the first and only line, there are two space separated integers, start, and n.
Sample Case 0
Sample Input
STDIN Function 2 4 start = 2, n = 4
Sample Output
2 4 6 8
Explanation The function must return a list of the 4 smallest even integers that are greater than or equal to 2, sorted into ascending order: 2,4,6, and 8.
Below is my code so far, but it only prints the even number within the range of the list not the length which is mentioned in the list:-
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))
I believe you're running into trouble when in the range declaration.
for i in range(start, n):
This could probably be rewritten to range(start, start + n) . With some changes to your loop logic, this reasoning will get you there.
A different approach to this problem could be to determine whether of not the start val is even or not and then adding even numbers to it. In the solution below, the meaning of length is more clearly represented.
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))
Your code is mostly wrong. Do it like this:
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, n):
if start % 2:
start += 1 # If odd, start from the next even
return [x for x in range(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))
Your code is almost ok. You only need a few changes in this part.
for i in range(start, start+2*n):
if i % 2 == 0:
count.append(i)
return count
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.