I have tried to write an if/else statement check if the 2 lists I'm working with don't share any values. If they don't, I want to return an empty list. I can't work out how. Whenever I add in the statement if messes up my code to print inside the function and prints it the about of times a list item was entered or says invalid syntax.
The program is supposed to compare 2 lists, only print out the numbers they share in the list, only print single numbers if they repeat. If an empty string is entered, exit the program. If the lists don't share numbers print an empty list e.g Output: [] This is what I have so far. Should I also be using a return statement instead of print?
def mylist(list1,list2):
same_num = []
for i in list1:
if i in list2:
same_num.append(i) #put matching numbers into a list
output = set(same_num) #convert to a set where no 2 thing will be the same
output_list = list(output) #convert back to list for output
print("Output: ", *output_list)
else:
print("Output: ", same_num)
ui1 = input('List 1: ')
if ui1 == "":
print(" ")
else:
ui2 = input('List 2: ')
list1 = list(ui1)
list2 = list(ui2)
mylist(list1, list2)
CodePudding user response:
The simplest way to do this:
def common(xs, ys):
return list(set(xs).intersection(set(ys)))
xs = [...]
ys = [...]
print(common(xs, ys))
CodePudding user response:
As you figured out already, you want to use a set for doing that. Sets keep only the unique elements and implement more efficient algorithms to check for intersection. In your case:
def mylist(list1,list2):
res = set(list1).intersection(set(list2))
print("Output: ", *res)
return
CodePudding user response:
Some remarks:
- If you want to exit when the input is empty, you need a loop for when it is not.
- As
inputreturns a string, callinglist()on it will produce a list with separate characters. You don't want to separate '19 25' into ['1', '9', ' ', '2', '5'], so first split into words, then map those words to numbers. - To get unique values (removing duplicates), use a
set. To get values which are common in both lists, use theintersectionmethod on the set.
Here is how it could look:
ui1 = input('List 1: (enter to quit)').split()
while ui1:
ui2 = input('List 2: ').split()
list1 = list(map(int, ui1))
list2 = list(map(int, ui2))
result = list(set(list1).intersection(list2))
print(result)
# Again: ...
ui1 = input('List 1: ').split()
