Conditionally combine or delete tuples in list - python

I have a list of data in Python of the form [(x0, f0), ..., (xn, fn)], where the tuple (xi, fi) represents the location and magnitude, respectively, of the ith element. For example:
point_forces = [(0, 4), (3.5, 2), (0, -3.1), (4, 6), (2, 0), (3.5, -4)]
What is a good way to remove tuples where fi = 0 and combine fi + fj of tuples where xi = xj, returning a result in the form [(x0, f0), ..., (xm, fm)]? Continuing the example, this is what I want to get:
result = [(0, 0.9), (3.5, -2), (4, 6)]
The order in which these operations are applied or the order in which tuples appear in the resultant list does not matter to me as long as xi ≠ xj and fi ≠ 0 for all i, j in [0, m].

Try:
out = {}
for x, f in point_forces:
if f != 0.0:
out[x] = out.get(x, 0) + f
out = [(x, round(f, 2)) for x, f in out.items() if f != 0.0] # if you want to keep the resulting tuples where f=0 then remove the if... part
print(out)
Prints:
[(0, 0.9), (3.5, -2), (4, 6)]

Related

Python zip function in Matlab

I have some Python code that I would like to run in Matlab. Suppose you have two lists of the same length:
x = [0, 2, 2, 5, 8, 10]
y = [0,2, 4, 7, 3, 3]
P = np.copy(y)
P.sort()
P = np.unique(P, axis=0) # P = [0 2 3 4 7] Takes the list y, sorts it and removes repeated elements
s = list(zip(x,y)) #match list x with y: s = [(0, 0), (2, 2), (2, 4), (5, 7), (8, 3), (10, 3)]
for y_1,y_2 in zip(P,P[1:]): # runs over (0, 2), (2, 3), (3, 4), (4, 7)
for v_1,v_2 in zip(s, s[1:]):
-- process --
Where in this case:
list(zip(s, s[1:])) = [((0, 0), (2, 2)), ((2, 2), (2, 4)), ((2, 4), (5, 7)), ((5, 7), (8, 3)), ((8, 3), (10, 3))]
I would like to translate this in Matlab but I don't know how to replicate the zip function. Any ideas on how I can do this?
MATLAB doesn’t have a zip, but you can accomplish the same thing in various ways. I think that the simplest translation of
for y_1,y_2 in zip(P,P[1:]):
...
is
for ii = 1:numel(P)-1
y_1 = P(ii);
y_2 = P(ii+1);
...
And in general, iterating over zip(x,y) is accomplished by iterating over indices 1:numel(x), then using the loop index to index into the arrays x and y.
Here's an implementation of Python's zip function in Matlab.
function out = zip(varargin)
% Emulate Python's zip() function.
%
% Don't actually use this! It will be slow. Matlab code works differently.
args = varargin;
nArgs = numel(args);
n = numel(args{1});
out = cell(1, n);
for i = 1:n
blah = cell(1, nArgs);
for j = 1:nArgs
if iscell(args{j})
blah(j) = args{j}(i);
else
blah{j} = args{j}(i);
end
end
out{i} = blah;
end
end
But don't use it; the performance will be lousy. In Matlab, you want to keep things in parallel primitive arrays instead, and use vectorized operations on those. Or, if you have to, iterate over array indexes.

Simulate a liquid flow through a randomly created square matrix that contains a set of integers from 0-9 using Python [duplicate]

This question already has an answer here:
Stimulating Liquid Flow on Matrix
(1 answer)
Closed 2 years ago.
Simulate a liquid flow through a randomly created square matrix that contains a set of integers from 0-9 using Python. The liquid should start from the top left corner of the matrix. It could only move towards right or below adjacent matrix. The lower value of the adjacent matrix, the higher potential for it to flow. In the case of the right and below adjacent matrix have the same value, the program should be able to simulate both conditions (Refer attached example image). The movement of the liquid is considered stop at the right or below edge of the matrix. The program should be able to show the sum of all numbers that the liquid has pass through, in all possibilities and visualize the path. Visualization can be done by replacing the numbers lying in the path with asterisk (*) , vertical line/pipe symbol (|), hyphen (-) or other relevant symbols such as (~,>= etc). Other methods to visualize can be accepted. Example output should look like this:
Example output visualization
This is what i have coded so far, but it does not output all the possible outcomes and the sum of integers in which the liquid flows through;
import random
import numpy as np
import copy
a=[]
n=int(input("Enter matrix size between 8 to 20 only= "))
while True:
if n<8:
n=int(input("Input size less than 8! Enter at least 8 or more = "))
elif n>20:
n=int(input("Input size more than 20! Enter at most 20 or lesser = "))
else:
break
print()
print(f'{n} × {n} matrix generated from random numbers of 0-9 :\n')
def create_matrix(n, a):
for i in range (n):
v=[]
for j in range (n):
v.append(random.randint(0,9))
a.append(v)
my.create_matrix(n, a)
b=copy.deepcopy(a)
#c=copy.deepcopy(a)
def print_array(n, array):
for i in range(n):
for j in range(n):
print(array[i][j], end=" ")
print()
print()
my.print_array(n, a)
def move_right(b, i, j, n):
b[0][0]="."
while i+1 < n and j+1<n :
if b[i+1][j] < b[i][j+1]:
b[i+1][j]="."
i+=1
elif b[i][j+1] < b[i+1][j]:
b[i][j+1]="."
j+=1
elif b[i+1][j] == b[i][j+1]:
b[i][j]="*"
#c=copy.deepcopy(b)
#move_bottom(c, i, j, n)
b[i][j+1]="."
j+=1
else:
break
def move_bottom(array,i ,j, n):
array[i][j]="."
alt=0
while i+1 < n and j+1<n :
if array[i+1][j] < array[i][j+1]:
array[i+1][j]="."
i+=1
elif array[i][j+1] < array[i+1][j]:
array[i][j+1]="."
j+=1
elif array[i+1][j] == array[i][j+1]:
array[i][j]="*"
bb=copy.deepcopy(array)
move_right(bb,i,j,n)
array[i+1][j]="."
i+=1
alt+=1
else:
break
print_array(n, array)
my.move_bottom(b, 0, 0, n)
I really need help with my coding so that i can output all the possible outcomes that the liquid can flow and the sum of integers in which the liquid flows through. If there's any other way to easily code this program using python given the conditions, please let me know!
Here is how you could do this for all possible ways.
A map of
456
867
978
would be represented as dictionary of dictionaries:
{ (0,0): {(1,0): {(2,0): {},
(1,1): { (2,1): {},
(1,2): {}}}}
and can be used to generate all paths from it.
Then you need a copy of the original numbers and can add the ascii art instead of the numbers at the correct positions. The total map has to check if you add another way to a formerly already set position, and if so replace it with a "both-ways" marker.
Some utility-methods:
import random
import copy
random.seed(42) # fixed for repeatability
class Consts:
"""Some constants to use throughout"""
VALUES = range(10)
SIZE = 8
START = (0,0)
OUT_OF_BOUNDS = 99
def generate():
"""Generates an Consts.SIZE * Consts.SIZE list of lists of numbers 0-9"""
n = Consts.SIZE
data = random.choices(Consts.VALUES, k = n*n)
return [data[i * n : i * n + n] for i in range(n)]
def v(data, x, y):
"""Returns the value in data at position x,y or
Consts.OUT_OF_BOUNDS if out of bounds."""
try:
return data[y][x]
except:
return Consts.OUT_OF_BOUNDS
def peek_east(data, pos):
"""Returs the value, position tuple of the position one to the east"""
new_pos = pos[0] + 1, pos[1]
return v(data, *new_pos), new_pos
def peek_south(data, pos):
"""Returs the value, position tuple of the position one to the south"""
new_pos = pos[0], pos[1] + 1
return v(data, *new_pos), new_pos
def done(pos):
"""Returns True if a position is at the border of the map"""
return Consts.SIZE-1 in pos
def pp(arr):
"""Pretty print a map / list of lists"""
print('\n'.join(''.join(map(str, n)) for n in arr))
the exploration part:
def explore(data, start=None, ways=None):
"""Creates/Explores all the ways. The exploration position are stored
as dictionary that contains all explored tiles as a dict of dict of ...
of possible ways to go through the map."""
size = Consts.SIZE
OUT = Consts.OUT_OF_BOUNDS
start = start or Consts.START
ways = ways or {}
pos = start
if done(pos):
ways[pos] = "DONE"
return
routes = []
# get east and south data to see where we can go from here
east, east_pos = peek_east(data, pos)
south, south_pos = peek_south(data, pos)
# where to move to
if east <= south:
routes.append(east_pos)
if east >= south:
routes.append(south_pos)
# add the visited tiles and the empty dicts for them to ways
for way in routes:
if pos not in ways:
ways[pos] = {}
if way not in ways:
ways[way] = {}
ways[pos][way] = ways[way]
# explore further
for way in routes:
explore(data, way, ways)
# simplify dict, only return the (0,0) element
return {Consts.START: ways[Consts.START]}
How to use it & ascii art:
array = generate()
pp(array)
exp = explore(array)
# used to create all possible paths from the dict we generated
def get_paths(tree, cur=()):
""" Source: https://stackoverflow.com/a/11570745/7505395 """
if not tree or tree == "DONE":
yield cur
else:
for n, s in tree.items():
for path in get_paths(s, cur+(n,)):
yield path
p = list(get_paths(exp))
# copy the original map for a "all in one" map
d_all = copy.deepcopy(array)
for path in p:
# copy the original map for this paths map
d = copy.deepcopy(array)
# get from,to pairs from this runway
for (_from, _to) in zip(path, path[1:]):
_, pe = peek_east(array, _from)
_, ps = peek_south(array, _from)
# ASCII Art the map
if _to == pe:
d[_from[1]][_from[0]] = "-"
d_all[_from[1]][_from[0]] = "-" if isinstance(d_all[_from[1]][_from[0]], int) else ("-" if d_all[_from[1]][_from[0]] == "-" else "+")
else:
d[_from[1]][_from[0]] = "|"
d_all[_from[1]][_from[0]] = "|" if isinstance(d_all[_from[1]][_from[0]], int) else ("|" if d_all[_from[1]][_from[0]] == "|" else "+")
# ASCII Art the last one
d[_to[1]][_to[0]] = "°"
d_all[_to[1]][_to[0]] = "°"
# print this map
print("\nPath: ", path)
pp(d)
# and total map
print("\nTotal mapping")
pp(d_all)
Output:
60227680
40250165
25808631
93008687
59358685
70220212
63322966
17139656
Path: ((0, 0), (1, 0), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1),
(6, 2), (7, 2))
-|227680
4-----|5
258086-°
93008687
59358685
70220212
63322966
17139656
Path: ((0, 0), (1, 0), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (5, 2),
(6, 2), (7, 2))
-|227680
4----|65
25808--°
93008687
59358685
70220212
63322966
17139656
Path: ((0, 0), (1, 0), (1, 1), (2, 1), (3, 1), (3, 2), (3, 3), (3, 4),
(3, 5), (4, 5), (5, 5), (6, 5), (7, 5))
-|227680
4--|0165
258|8631
930|8687
593|8685
702----°
63322966
17139656
Path: ((0, 0), (1, 0), (1, 1), (2, 1), (3, 1), (3, 2), (3, 3), (3, 4),
(3, 5), (4, 5), (4, 6), (5, 6), (6, 6), (6, 7))
-|227680
4--|0165
258|8631
930|8687
593|8685
702-|212
6332--|6
171396°6
Path: ((0, 0), (1, 0), (1, 1), (2, 1), (3, 1), (3, 2), (3, 3), (3, 4),
(3, 5), (4, 5), (4, 6), (5, 6), (5, 7))
-|227680
4--|0165
258|8631
930|8687
593|8685
702-|212
6332-|66
17139°56
Path: ((0, 0), (1, 0), (1, 1), (2, 1), (3, 1), (3, 2), (3, 3), (3, 4),
(3, 5), (4, 5), (4, 6), (4, 7))
-|227680
4--|0165
258|8631
930|8687
593|8685
702-|212
6332|966
1713°656
Total mapping
-|227680
4--+-+|5
258|8--°
930|8687
593|8685
702-+--°
6332++|6
1713°°°6

Remove duplicate unordered tuples from list

In a list of tuples, I want to have just one copy of a tuple where it may be (x, y) or (y, x).
So, in:
# pairs = list(itertools.product(range(3), range(3)))
pairs = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
the result should be:
result = [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)] # updated pairs
This list of tuples is generated using itertools.product() but I want to remove the duplicates.
My working solution:
pairs = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
result = []
for pair in pairs:
a, b = pair
# reordering in increasing order
temp = (a, b) if a < b else (b, a)
result.append(temp)
print(list(set(result))) # I could use sorted() but the order doesn't matter
How can this be improved?
You could use combinations_with_replacement
The code for combinations_with_replacement() can be also expressed as a subsequence of product() after filtering entries where the elements are not in sorted order (according to their position in the input pool)
import itertools
pairs = list(itertools.combinations_with_replacement(range(3), 2))
print(pairs)
>>> [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]
edit I just realized, your solution matches my solution. What you are doing is just fine. If you need to do this for a very large list, then there are some other options you may want to look into, like a key value store.
If you need to remove dupes more programatically, then you can use a function like this:
def set_reduce(pairs):
new_pairs = set([])
for x,y in pairs:
if x < y:
new_pairs.add((x,y))
else:
new_pairs.add((y,x))
return new_pairs
running this results in
>>>set_reduce(pairs)
set([(0, 1), (1, 2), (0, 0), (0, 2), (2, 2), (1, 1)])
This is one solution which relies on sparse matrices. This works for the following reasons:
An entry in a matrix cannot contain two values. Therefore, uniqueness is guaranteed.
Selecting the upper triangle ensures that (0, 1) is preferred above (1, 0), and inclusion of both is not possible.
import numpy as np
from scipy.sparse import csr_matrix, triu
lst = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1),
(1, 2), (2, 0), (2, 1), (2, 2)]
# get row coords & col coords
d1, d2 = list(zip(*lst))
# set up sparse matrix inputs
row, col, data = np.array(d1), np.array(d2), np.array([1]*len(lst))
# get upper triangle of matrix including diagonal
m = triu(csr_matrix((data, (row, col))), 0)
# output coordinates
result = list(zip(*(m.row, m.col)))
# [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]

Finding a sequence of alternating numbers in a list

I'm currently trying to implement the Fourth Nelson rule from:
https://en.wikipedia.org/wiki/Nelson_rules
I.e. given a list of numbers of length N, I want to know if there exists a consecutive sequence of numbers that are alternating in direction of length n. 'Alternating' means consecutive numbers go up, then down, then up, etc.
My data is in (t,x) tuples. 't' stands for the time axis, always increasing. 'x' is the value associated with the time and the series we are concerned with. For example:
data = [(0, 2.5), (1, 2.1), (2, 1.7), (3, 2.0), (4, 0.3), (5, 0.8), (6, -1.2), (7, -0.5)]
Here, the alternating x value sequence is for everything but the first tuple. See the below graph:
The alternating sequence is highlighted in red. The rule looks for 14 points in a row, but I want to generalize this to n-points in a row. (n < N) I can't just output True or False, I want to output the tuple of points that satisfy the condition. In other words, the output would be:
outliers = [(1, 2.1), (2, 1.7), (3, 2.0), (4, 0.3), (5, 0.8), (6, -1.2), (7, -0.5)]
I've tried a few things, none of which resulted in the desired output. These included things like np.diff() and np.sign(). I have a feeling itertools() can do this, but I can't quite get there.
Any input is greatly appreciated.
Here's a first cut at your algorithm in straight Python:
data = [(0, 2.5), (1, 2.1), (2, 1.7), (3, 2.0), (4, 0.3), (5, 0.8), (6, -1.2), (7, -0.5)]
n = 5
t0, x0 = data.pop(0)
outliers = []
up = bool(x0 > 0)
for t, x in data:
if (x < x0 and up) or (x > x0 and not up):
if not outliers:
outliers = [(t0,x0)]
outliers.append((t,x))
up = not up
else:
if len(outliers) >= n:
print 'outliers =', outliers
outliers = []
t0,x0 = t,x
if len(outliers) >= n:
print 'outliers =', outliers

Add tuple to list of tuples in Python

I am new to python and don't know the best way to do this.
I have a list of tuples which represent points and another list which represents offsets. I need a set of all the combinations that this forms.
Here's some code:
offsets = [( 0, 0),( 0,-1),( 0, 1),( 1, 0),(-1, 0)]
points = [( 1, 5),( 3, 3),( 8, 7)]
So my set of combined points should be
[( 1, 5),( 1, 4),( 1, 6),( 2, 5),( 0, 5),
( 3, 3),( 3, 2),( 3, 4),( 4, 3),( 2, 3),
( 8, 7),( 8, 6),( 8, 8),( 9, 7),( 7, 7)]
I'm not able to use NumPy or any other libraries.
result = [(x+dx, y+dy) for x,y in points for dx,dy in offsets]
For more, see list comprehensions.
Pretty simple:
>>> rslt = []
>>> for x, y in points:
... for dx, dy in offsets:
... rslt.append( (x+dx, y+dy) )
...
>>> rslt
[(1, 5), (1, 4), (1, 6), (2, 5), (0, 5), (3, 3), (3, 2), (3, 4), (4, 3), (2, 3), (8, 7), (8, 6), (8, 8), (9, 7), (7, 7)]
Cycle through the points and the offsets, then build new tuples of adding the offsets to the points.
Personally, I like Alok's answer. However, for fans of itertools, the itertools-based equivalent (in Python 2.6 and later) is:
import itertools as it
ps = [(x+dx, y+dy) for (x, y), (dx, dy) in it.product(points, offsets)]
However, in this case the itertools solution is not faster than the simple one (it's actually a tad slower because it needs to unpack each x, y repeatedly for every offset, while Alok's simple approach unpacks each x, y but once). Still, itertools.product is an excellent alternative to nested loops in other cases, so, it's worth knowing about it!-)
If you don't care about duplicates in the result:
result = []
for ox, oy in offsets:
for px, py in points:
result.append((px + ox, py + oy))
If you do care about duplicates in the result:
result = set()
for ox, oy in offsets:
for px, py in points:
result.add((px + ox, py + oy))

Categories

Resources