10.0k views
1 vote
MyProgramming Lab

It needs to be as simple as possible. Each question is slightly different.

1. Given the lists list1 and list2, not necessarily of the same length, create a new list consisting of alternating elements of list1 and list2 (that is, the first element of list1 followed by the first element of list2 , followed by the second element of list1, followed by the second element of list2, and so on. Once the end of either list is reached, the remaining elements of the longer list is added to the end of the new list. For example, if list1 contained [1, 2, 3] and list2 contained [4, 5, 6, 7, 8], then the new list should contain [1, 4, 2, 5, 3, 6, 7, 8]. Associate the new list with the variable list3.

2. Given the lists list1 and list2 that are of the same length, create a new list consisting of the last element of list1 followed by the last element of list2, followed by the second to last element of list1, followed by the second to last element of list2, and so on (in other words the new list should consist of alternating elements of the reverse of list1 and list2). For example, if list1 contained [1, 2, 3] and list2 contained [4, 5, 6], then the new list should contain [3, 6, 2, 5, 1, 4]. Associate the new list with the variable list3.

3. Given the lists list1 and list2, not necessarily of the same length, create a new list consisting of alternating elements of list1 and list2 (that is, the first element of list1 followed by the first element of list2, followed by the second element of list1, followed by the second element of list2, and so on. Once the end of either list is reached, no additional elements are added. For example, if list1 contained [1, 2, 3] and list2 contained [4, 5, 6, 7, 8], then the new list should contain [1, 4, 2, 5, 3, 6]. Associate the new list with the variable list3.

User Zmorris
by
3.4k points

1 Answer

6 votes

Answer:

Step-by-step explanation:

The following code is written in Python. It creates a method for each one of the questions asked and then tests all three with the same test case which can be seen in the picture attached below.

def alternating_list(lst1, lst2):

lst3 = []

for x in range(len(lst1)):

lst3.append(lst1[x])

try:

lst3.append(lst2[x])

except:

pass

if len(lst2) > len(lst1):

lst3.extend(lst2[len(lst1):])

return lst3

def reverse_alternating(lst1, lst2):

lst3 = []

if len(lst1) == len(lst2):

for x in range(len(lst1) - 1, -1, -1):

lst3.append(lst1[x])

lst3.append(lst2[x])

return lst3

def alternating_list_no_extra(lst1, lst2):

lst3 = []

max = 0

if len(lst1) > len(lst2):

max = len(lst2)

else:

max = len(lst1)

for x in range(max):

lst3.append(lst1[x])

try:

lst3.append(lst2[x])

except:

pass

return lst3

MyProgramming Lab It needs to be as simple as possible. Each question is slightly-example-1
User Iya
by
3.8k points