emphasized textI want to append two lists together if the difference between the values in the new appended list will be 1. For example, if my second list is [8, 7, 6] then I would add it to my first list while removing all the numbers from the second list.
num = [10, 9]
current_nums = [8, 7, 6]
#after appending
num = [10, 9, 8, 7, 6]
current_nums = #empty
Here is what I have tried so far:
def add(self, num):
if len(self.current_nums) > 0:
num.append(self.current_nums)
difference = []
for i in range(1, len(self.num)):
difference.append(self.num[i] - self.num[i-1])
res = difference.count(difference[0]) == len(difference)
if res == True:
self.current_nums.pop()
When I try to append the first list to the second list I get an AttributeError: type object 'Board' has no attribute 'append'. How can I append a list to a class object?
CodePudding user response:
class ExtendList:
"""class with methods to extend first list by second list and empty the second list
Attributes:
list1: first list
list2: second list
"""
def __init__(self, list1: list, list2: list) -> None:
self.list1: list = list1
self.list2: list = list2
def extend_list1_and_empty_list2(self) -> None:
"""extend list 1 and empty list 2"""
self.list1.extend(self.list2)
self.empty_list2()
def empty_list2(self) -> None:
"""empty list 2"""
self.list2 = []
list_obj: ExtendList = ExtendList([10, 9], [8, 7, 6])
list_obj.extend_list1_and_empty_list2()
print(list_obj.list1)
print(list_obj.list2)
CodePudding user response:
Here is my solution:
list1 = [10, 9]
list2 = [8, 7, 6]
list3 = list1
kt = True
for i in range(0, len(list2)):
list1.append(list2[i])
for i in range(0, len(list2)-1):
if list1[i] - list1[i 1] != 1:
kt = False
if kt:
list2=[0]
else:
list1 = list3
Firstly, you want to add list2 to list1. It is quite easy then. In this program, I use a for loop and an "append" function.
Secondly, you want to check if the difference between the values is one. You can do this using a for loop and a boolean variable. If the difference is not one then you want to return the old list1. That's why the list3 is there.