I have the general idea of how to do this in Java, but I am learning Python and not sure how to do it.
I need to implement a function that returns a list containing
def skip_elements(elements):
new_list = []
for index,element in enumerate(elements):
if index == 0:
new_list.append(element)
elif (index % 2) == 0:
new_list.append(element)
return new_list
Also can use for loop + enumerate. elif (index % 2) == 0: ## Checking if number is even, not odd cause indexing starts from zero not 1.
def skip_elements(elements):
new_list = [ ]
i = 0
for element in elements:
if i%2==0:
c=elements[i]
new_list.append(c)
i+=1
return new_list
def altElement(a):
return a[::2]
Using the for-loop like you have, one way is this:
def altElement(a):
b = []
j = False
for i in a:
j = not j
if j:
b.append(i)
print b
j just keeps switching between 0 and 1 to keep track of when to append an element to b.
def skip_elements(elements):
# Initialize variables
i = 0
new_list=elements[::2]
return new_list
# Should be ['a', 'c', 'e', 'g']:
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
# Should be ['Orange', 'Strawberry', 'Peach']:
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))
# Should be []:
print(skip_elements([]))
Alternatively, you could do:
for i in range(0, len(a), 2):
#do something
The extended slice notation is much more concise, though.