Related
I have a list=[1,2,3,4]
And I only want to receive tuple results for like all the positions in a matrix, so it would be
(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,1),(3,2),(3,3),(3,4),(4,1),(4,2),(4,3),(4,4)
I've seen several codes that return all the combinations but i don't know how to restrict it only to the tuples or how to add the (1,1),(2,2),(3,3),(4,4)
Thank you in advance.
You just need a double loop. A generator makes it easy to use
lst = [1,2,3,4]
def matrix(lst):
for i in range(len(lst)):
for j in range(len(lst)):
yield lst[i], lst[j]
output = [t for t in matrix(lst)]
print(output)
Output:
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]
If you just want to do this for making pairs of all symbols in the list
tuple_pairs = [(r,c) for r in lst for c in lst]
If you have instead some maximum row/colum numbers max_row and max_col you could avoid making the lst=[1,2,3,4] and instead;
tuple_pairs = [(r,c) for r in range(1,max_row+1) for c in range(1,max_col+1)]
But that's assuming that the lst's goal was to be = range(1, some_num).
Use itertools.product to get all possible combinations of an iterable object. product is roughly equivalent to nested for-loops with depth specified by the keyword parameter repeat. It returns an iterator.
from itertools import product
lst = [1, 2, 3, 4]
combos = product(lst, repeat=2)
combos = list(combos) # cast to list
print(*combos, sep=' ')
Diagonal terms can be found in a single loop (without any extra imports)
repeat = 2
diagonal = [(i,)*repeat for i in lst]
print(*diagonal sep=' ')
You can do that using list comprehension.
lst=[1,2,3,4]
out=[(i,i) for i in lst]
print(out)
Output:
[(1, 1), (2, 2), (3, 3), (4, 4)]
For example i have a tuple
t = ((1, 1), (1, 1), (1, 1))
How can i get sum of all this elements with only one loop
I would like to get
6
You can map with sum, and get the sum of the result:
sum(map(sum, t))
# 6
Or if you prefer it with a for loop:
res = 0
for i in t:
res += sum(i)
print(res)
# 6
You can use simple iteration (works in python3.8, I assume it works on older versions as well).
t = ((1, 1), (1, 1), (1, 1))
sum_tuples = 0
for a,b in t:
sum_tuples += a # First element
sum_tuples += b # Second Element
print(sum_tuples) # prints 6
You could use itertools.chain
>>> import itertools
>>> t = ((1, 1), (1, 1), (1, 1))
>>> sum(itertools.chain.from_iterable(t))
6
You can loop tuple to sum all. This code is long but it can sum tuple in tuple.
t = ((1, 1), (1, 1), (1, 1))
# Tuple in tuple:
t = ((1, 1, (1, 1, (1, 1))))
def getsum(var, current = 0):
result = current
if type(var) == tuple:
for i in range(len(var)):
x = var[i]
result = getsum(x, result)
else:
result += var
return result
print(getsum(t))
I just wondered how can you iterate through a nested Leftsequence?
I made a left sequence out with the following code:
def leftSeq(s):
ls = "leer"
for i in range(len(s), 0, -1):
ls = (l[i - 1], ls)
return ls
l = [1,2,3]
Output = (1, (2, (3, 'leer')))
How do I iterate through it?
You could make an iterator for such left sequences:
def left_iterator(lseq):
while isinstance(lseq,tuple) and len(lseq) == 2:
first, lseq = lseq
yield first
yield lseq
#test:
x = (1, (2, (3, 'leer')))
for i in left_iterator(x):
print(i)
Output:
1
2
3
leer
You could use a while loop like so and nest through ls:
x = (1, (2, (3, 'leer'))) #=leftSeq(l)
while len(x) > 1:
print(x)
x = x[1]
(1, (2, (3, 'leer')))
(2, (3, 'leer'))
(3, 'leer')
leer
I am trying to get the combination of 10 numbers in sequences of 4's in python.
import itertools
combs = (itertools.permutations ([1,2,3,4,5,6,7,8,9,10], 4))
When I run it, it says start then skips 2 lines and doesn't do anything. Can you please tell me what is wrong?
permutations return iterator. You should iterator over it to get values.
import itertools
combs = itertools.permutations ([1,2,3,4,5,6,7,8,9,10], 4)
for xs in combs:
print(xs)
Or use list to get result as list:
import itertools
combs = itertools.permutations ([1,2,3,4,5,6,7,8,9,10], 4)
list(combs) # => [(1,2,3,4), ...., (10,9,8,7)]
itertools.permutations returns an iterator, to fetch items from it you can either use list() or loop on it.
Demo:
list():
>>> list(itertools.permutations ([1,2,3], 2))
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
for-loop:
>>> for x in itertools.permutations ([1,2,3], 2):
... print x
...
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
And yes print is required if you want to see any output from your program. In python shell print is not required as it echoes back the return value, but when executing the program from a .py file print is required to see any output.
import itertools
combs = list(itertools.permutations ([1,2,3,4,5,6,7,8,9,10], 4))
print combs
Is there a Python function an "outer-zip", which is a extension of zip with different default values for each iterable?
a = [1, 2, 3] # associate a default value 0
b = [4, 5, 6, 7] # associate b default value 1
zip(a,b) # [(1, 4), (2, 5), (3, 6)]
outerzip((a, 0), (b, 1)) = [(1, 4), (2, 5), (3, 6), (0, 7)]
outerzip((b, 0), (a, 1)) = [(4, 1), (5, 2), (6, 3), (7, 1)]
I can almost replicate this outerzip function using map, but with None as the only default:
map(None, a, b) # [(1, 4), (2, 5), (3, 6), (None, 7)]
Note1: The built-in zip function takes an arbitrary number of iterables, and so should an outerzip function. (e.g. one should be able to calculate outerzip((a,0),(a,0),(b,1)) similarly to zip(a,a,b) and map(None, a, a, b).)
Note2: I say "outer-zip", in the style of this haskell question, but perhaps this is not correct terminology.
It's called izip_longest (zip_longest in python-3.x):
>>> from itertools import zip_longest
>>> a = [1,2,3]
>>> b = [4,5,6,7]
>>> list(zip_longest(a, b, fillvalue=0))
[(1, 4), (2, 5), (3, 6), (0, 7)]
You could modify zip_longest to support your use case for general iterables.
from itertools import chain, repeat
class OuterZipStopIteration(Exception):
pass
def outer_zip(*args):
count = len(args) - 1
def sentinel(default):
nonlocal count
if not count:
raise OuterZipStopIteration
count -= 1
yield default
iters = [chain(p, sentinel(default), repeat(default)) for p, default in args]
try:
while iters:
yield tuple(map(next, iters))
except OuterZipStopIteration:
pass
print(list(outer_zip( ("abcd", '!'),
("ef", '#'),
(map(int, '345'), '$') )))
This function can be defined by extending each inputted list and zipping:
def outerzip(*args):
# args = (a, default_a), (b, default_b), ...
max_length = max( map( lambda s: len(s[0]), args))
extended_args = [ s[0] + [s[1]]*(max_length-len(s[0])) for s in args ]
return zip(*extended_args)
outerzip((a, 0), (b, 1)) # [(1, 4), (2, 5), (3, 6), (0, 7)]