Subtracting one list from another in Python [duplicate] - python

This question already has answers here:
Remove all the elements that occur in one list from another
(13 answers)
Closed 5 years ago.
What I want to happen: When given two lists (list a and list b), remove the numbers in list a that are in list b.
What currently happens: My first function works only if list a has only one number to be removed.
What I've tried: Turning the lists into sets, then subtracting a - b
def array_diff(a, b):
c = list(set(a) - set(b))
return c
Also tried: Turning the list into sets, looking for n in a and m in b, then if n = m to remove n.
def array_diff(a, b):
list(set(a))
list(set(b))
for n in (a):
for m in (b):
if n == m:
n.remove()
return a
Possibly thought about: Using the "not in" function to determine if something is in b or not.
Sample Input/Output:
INPUT: array_diff([1,2], [1]) OUTPUT: [2]
INPUT: array_diff([1,2,2], [1]) OUTPUT: [2] (This should come out to be [2,2]

Just use it like that :
c = [x for x in a if x not in b]

Related

printing a new list as product of elements in two lists [duplicate]

This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Element-wise addition of 2 lists?
(17 answers)
Closed 28 days ago.
So i'm trying to define a function which given two lists of the same size, returns a new list with the product of each element at a given index.
a = [1, 2, 3]
b = [1, 4, 5]
def list_mult(a, b):
if len(a) != len(b):
print("error, lists must be the same size")
for i in range(len(a)):
return [a[i] * b[i]]
print(list_mult(a, b))
The code is running, but it is only returning [1]. Not sure why, as I was under the impression that this for loops iterates over all i's in the range.
Don't return from inside the loop, as that will return after only 1 iteration. Keeping your current structure, you can instead add each product to a list and return that.
res = []
for i in range(len(a)):
res.append(a[i] * b[i])
return res
Alternatively, use a list comprehension with zip.
return [x * y for x, y in zip(a, b)]
Here's how I would solve the problem, catering for the edgecase of one array being larger than the other.
from typing import List
def multiply_arrays(a: List[int], b: List[int]):
result = []
for i in range(max(len(a), len(b))):
item_a = a[i] if i < len(a) else 1
item_b = b[i] if i < leb(b) else 1
result.append(item_a * item_b)
return result

Removing elements from lists to speed up list comparison [duplicate]

This question already has answers here:
Python list intersection efficiency: generator or filter()?
(4 answers)
Closed 12 months ago.
Let's assume we have two lists containing unique values and want to find the values that are in both lists using list comprehension.
a = [1,3,5]
b = [3,5,7]
c = [x for x in a if x in b]
print(c)
[3,5]
Simple enough. Now, what if each list had 1 million elements that we wanted to compare? List comprehension would continue to compare every element in list a to every element in list b, even after it has found '5' (from the example above) in both lists. Is that correct?
Would removing an element from the lists when it is found in both lists be more efficient to shorten the comparison time as it loops? Or is there something else I've probably missed?
for x in a:
if x in b:
c.append(x)
a.remove(x)
b.remove(x)
print(a)
[1]
print(b)
[7]
print(c)
[3,5]
Removing x from your list a in
for x in a:
if x in b:
c.append(x)
a.remove(x)
b.remove(x)
would add extra time complexity for the removing of the item. Whenever you call the remove it's of O(n) complexity with n being the number of items in the list. You could write a second for loop which makes it a bit faster, because you could "break" whenever you find the element. However, I think the biggest performance gainer is using a set, because of the O(1) lookup time. You can read about a set here:
https://www.w3schools.com/python/python_sets.asp
https://stackoverflow.com/questions/7351459/time-complexity-of-python-set-operations#:~:text=According%20to%20Python%20wiki%3A%20Time,collisions%20and%20O(n). I wrote a little code snippet for you where you can test and also see the performance difference:
I import the performance counter from the time library to measure the time.
from time import perf_counter
I generate two lists with unique elements:
a = [x for x in range(10000)]
b = [x * 2 for x in range(10000)]
I measure the time from your operation mentioned above:
start_list = perf_counter()
c = [x for x in a if x in b]
stop_list = perf_counter()
print(f"Calculating with list operations took {stop_list - start_list}s")
I measure the time via set operations:
start_set = perf_counter()
d = list(set(a) & set(b))
stop_set = perf_counter()
print(f"Calculating with set operations took {stop_set - start_set}s")
Just to make sure the two methods give the same result:
assert c == d
Output:
Calculating with list operations took 0.796774061s
Calculating with set operations took 0.0013706330000000655s

python: how can I create something which generates all possible combinations in a form of tuples for integers from A and B [duplicate]

This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 2 years ago.
Question:
# Let A= {m | m is an integer satisfying 0 < m < 13} and
# B = {n | n is an integer satisfying 7 < n < 23}.
# I'm trying to generate all possible combinations of (A,B).
For example:
A= (1,2,3,4,5,6,7)
B =(7,8,9,10,11...)
Combination = (1,7),(1,8)(1,9)....(2,7),(2,8),(2,9).... and so forth
-I was thinking of using a for loop but could not seem to manage to get it working.
For the sake of simplicity you could just use :
for a in A:
for b in B:
print((a,b,))
or
combinations = [(a,b,) for a in A for b in B]
Use itertools.product, as in the below code:
import itertools
out = itertools.product(A, B)

Python: Use a Loop to Manipulate Arrays [duplicate]

This question already has answers here:
Extract first item of each sublist
(8 answers)
Closed 4 years ago.
I have to perform the same operation on a number of arrays. Is there a way to use a loop in Python to carry out this repetitive task?
For example, I have 5 arrays: A, B, C, D, and E.
I want to carry out the following:
A = A[0]
B = B[0]
C = C[0]
D = D[0]
E = E[0]
Is there any way to do this using a loop or some other technique to avoid typing almost the same thing multiple times?
My question has been marked as a duplicate of this question. There, the person is asking how to extract the first element from each list (or in my case array). I am not simply trying to extract the first element. I actually want to replace each array with it's first element -- literally A = A[0].
Some are saying this is not a good idea, but this is actually what I want to do. To give some context, I have code that leaves me with a number of 2D arrays, with shapes n x m. When n = 1, the first dimension is irrelevant, and I would like to dispense with that dimension, which is what A = A[0] does. My code needs to handle both cases where n = 1 and cases when n > 1.
In other words, when n = 1, my code results in an array A that is of the following form: A = array([[a]]), and I want to change it so that A = array([a]). And to reiterate, I need the flexibility of allowing n > 1, in which case A = array([[a1],[a2],...]). In that case, my code will not execute A = A[0].
The solution by Mark White below works, if you change the last line to:
A,B,C,D,E = [x[0] for x in [A,B,C,D,E]]
What's interesting is that this solution makes the code more compact, but actually involves as many characters as (an technically more than) the brute force approach.
I do think it is a pretty easy problem ,in my case ,I use three array ,but I think you can do five , my dear friend!
A = [1,3,4]
B = [2,4,5]
C = [54,5,6]
A,B,C = [x[0] for x in [A,B,C]]
Simply create a list of lists (or, specifically, references to A, B, C, etc.)
l = [A, B, C, D, E]
Then, you can iterate over l however you choose.
for i in range(len(l)):
l[i] = l[i][0]
Note that this will update l[i] rather than the lists (A, B, C, ...) themselves.

How to create a function that uses 2 integers from 2 different lists and adding the pair to a certain integer?

Doing some basic python coding. Here is the problem I was presented.
Create a function that takes 3 inputs:
Two lists of integers
one integer n
Prints the pairs of integers, one from the first input list and the other form the second list, that adds up to n. Each pair should be printed.
Final Result (Example):
pair([2,3,4], [5,7,9,12], 9)
2 7
4 5
I'm still awfully new to Python, studying for a test and for some reason this one keeps giving me some trouble. This is an intro course so basic coding is preferred. I probably won't understand most advanced coding.
The simplest naieve approach would be to just test all possible combinations to see if they add up.
def pair(list1, list2, x):
for a in list1:
for b in list2:
if a + b == x:
print a, b
There are more efficient ways to do it (eg. ignore duplicates, ignore numbers greater than x, etc.)
If you wanted to do it in a single loop, python has some convenience functions for that
from itertools import product
for a, b in product(list1, list2):
if a + b == x:
print a, b

Categories