I'd like to create a function that returns the elements of a list on odd positions or the negative elements of a list.
My solution works with the first assertion, but the second generates an AssertionError, because returns [-1, -2, 1] instead of [-1, -2]. Any suggestions?
def solution(input):
output = []
for item in input:
if item < 0:
output.append(item)
elif not item % 2 == 0:
output.append(item)
return output
assert solution([0,1,2,3,4,5]) == [1,3,5]
assert solution([1,-1,2,-2]) == [-1,-2]
You want the numbers on odd positions, but your %
check is checking the actual values in the list rather than their positions.
Try using enumerate
to get the index alongside the value as you iterate through the list:
def solution(input):
output = []
for ix, item in enumerate(input):
if item < 0 or ix % 2 != 0:
output.append(item)
return output
Also for completeness purpose you may want to consider adding this to your already existing code:
if any(i < 0 for i in output):
return [i for i in output if i < 0]
, since it tests if a negative exists and return only those if so. The answer by HumphreyTriscuit is, however, the better solution from my point of view.
One line to define solution function:
def solution(input):
return [input[pos] for pos in range(len(input)) if not pos %2 == 0 or input[pos] < 0]
print solution([0,1,2,3,4,5,7])
print solution([1,-1,2,-2, -3])
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.