Reverse loop inside a loop with same list - python

num = list(str(1234567))
for n1 in num:
print(n1)
for n2 in reversed(num):
print('\t', n2)
On each iteration, it prints the first digit from the first loop and all 7 from the reverse loop. How can I print not all digits but only the last (i.e first) digit from reverse loop?
Thanks

Simplest way is to just zip the forward and reverse lists together:
for n1, n2 in zip(num, reversed(num)):
print(n1, '\t', n2)

Here's a feeble attempt. Is this the kind of thing you're looking for?
for idx,i in enumerate(x):
print(i,"\t",x[-(idx+1)])

Do you mean like this?
num = list(str(1234567))
for i in range(len(num)):
print(num[i], '\t', num[-(i+1)])
Output is:
1 7
2 6
3 5
4 4
5 3
6 2
7 1

Nothing to do with Python, but here it is in Haskell :)
myDie = [1,2,3,4,5,6]
sevens = [ (x,y) | x <- myDie, y <- myDie, x+y == 7]

You should make a second list:
>>> num_rev = num[:]
>>> num_rev.reverse()
>>> num_rev
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Then do something like:
>>> for n1,n2 in zip(num,num_rev):
... print(n1, n2)
...
0 9
1 8
2 7
3 6
4 5
5 4
6 3
7 2
8 1
9 0

Related

How to derive the following pattern with Python

How can I make the following pattern with Python, I thought about everything, but I didn't get anywhere
Problem solved, thanks to all contributors
Why negativity?
Well, if stackoverflow is not for asking questions, then what is it for???
The displayed numbers are always the maximum of the row number and column number they appear at.
So, to print that pattern, you could do something line this:
def solve(n):
for row in range(1, n + 1):
for col in range(1, n + 1):
print(max(row, col), end=" ")
print("\n")
solve(5)
As you posted an image, it is not clear whether there should be empty lines between the lines with numbers, and whether at the end it is fine to have trailing newline characters or not.
Also check whether there are requirements as to how the pattern should look when the size of the matrix is more than 9.
But it should not be hard to adapt the code accordingly.
Here's another approach:
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
for j in range(i):
numbers[j] += 1
print(*numbers)
Output:
1 2 3 4 5
2 2 3 4 5
3 3 3 4 5
4 4 4 4 5
5 5 5 5 5
import numpy as np #Just to format as matrix when printing
a=[[max(r,c) for r in range(1,6)] for c in range(1,6)]
print(np.array(a))
>>> [[1 2 3 4 5]
>>> [2 2 3 4 5]
>>> [3 3 3 4 5]
>>> [4 4 4 4 5]
>>> [5 5 5 5 5]]

Python Ruler Sequence Generator

I have been struggling for a long time to figure how to define a generator function of a ruler sequence in Python, that follows the rules that the first number of the sequence (starting with 1) shows up once, the next two numbers will show up twice, next three numbers will show up three times, etc.
So what I am trying to get is 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7 etc.
I understand that the way to do this is to have two separate count generators (itertools.count(1)) and then for every number in one generator yield number from the other generator:
def rul():
num = itertools.count(1)
repeator = itertools.count(1)
for x in range(next(repeator)):
yield from num
But if I hit next() on this function, I get back just the regular 1,2,3,4.. sequence...
Any help on this would be appreciated.
how about regular old python with no itertools?
def ruler():
counter = 1
n = 1
while True:
for i in range(counter):
for j in range(counter):
yield n
n += 1
counter += 1
in my humble opinion this is the clearest and most straighforward solution for these types of situations
How about itertools.repeat?
import itertools
def ruler():
num = rep_count = 0
while True:
rep_count += 1
for i in range(rep_count):
num += 1
yield from itertools.repeat(num, rep_count)
You can obtain such a generator without writing your own function using count() and repeat() from itertools:
from itertools import repeat,count
i = count(1,1)
rul = (n for r in count(1,1) for _ in range(r) for n in repeat(next(i),r))
for n in rul: print(n, end = " ")
# 1 2 2 3 3 4 4 4 5 5 5 6 6 6 7 7 7 7 8 8 8 8 9 9 9 9 10 10 10 10 11 11 ...
If you want to go all in on itertools, you'll need count, repeat, and chain.
You can group the numbers in your sequence as follows, with
each group corresponding to a single instance of repeat:
1 # repeat(1, 1)
2 2 # repeat(2, 2)
3 3 # repeat(3, 2)
4 4 4 # repeat(4, 3)
5 5 5 # repeat(5, 3)
6 6 6 # repeat(6, 3)
7 7 7 7 # repeat(7, 4)
...
So we can define ruler_numbers = chain.from_iterable(map(repeat, col1, col2)), as long as we can define col1 and col2 appropriately.
col1 is easy: it's just count(1).
col2 is not much more complicated; we can group them similarly to the original seqeunce:
1 # repeat(1, 1)
2 2 # repeat(2, 2)
3 3 3 # repeat(3, 3)
4 4 4 4 # repeat(4, 4)
...
which we can also generate using chain.from_iterable and map:
chain.from_iterable(map(repeat, count(1), count(1))).
In the end, we get our final result in our best attempt at writing Lisp in Python :)
from itertools import chain, repeat, count
ruler_numbers = chain.from_iterable(
map(repeat,
count(1),
chain.from_iterable(
map(repeat,
count(1),
count(1)))))
or if you want to clean it up a bit with a helper function:
def concatmap(f, *xs):
return chain.from_iterable(map(f, *xs))
ruler_numbers = concatmap(repeat,
count(1),
concatmap(repeat,
count(1),
count(1)))

Python create a sequence of non repeating numbers

I want to create a sequence something like this [[1,2],[3,4],[5,6],..].
Here is what I tried and got:
n = 3 # I need three lists
for i in range(0,n+1,1):
print(i+1,i+2)
1 2
2 3
3 4
4 5
Expected output:
1 2
3 4
5 6
n = 3
pairs = [list([i, i + 1]) for i in range (1, 2 * n, 2)]
for pair in pairs:
for x in pair:
print(x, end = ' ')
print()
This prints:
1 2
3 4
5 6
And the list pairs so formed is:
[[1, 2], [3, 4], [5, 6]]
Take step of 2 and end at n*2
n=3
output = []
for i in range(0,n*2,2):
print(i+1,i+2)
output.append([i+1,i+2])
print(output)
1 2
3 4
5 6
[[1, 2], [3, 4], [5, 6]]
After a trial, I found the following answer:
for i in range(0,n,1):
print(2*i+1,2*i+2)

String-formatting two zipped NumPy arrays in Python 3

I would like to use pythons format function to print subsequent numbers of a numpy array.
I have got two numpy arrays, let's say:
x=[1 2 3 4]
y=[5 6 7 8]
Now I would like to print this:
1 5 2 6 3 7 4 8
I can almost achieve this by:
print('{} {} {} {}'.format(*zip(x,y)))
but it yields:
(1,5) (2,6) (3,7) (4,8)
Of course I could use
"{} {} {} {}".format(x[0], y[0], x[1], y[1])
and so on but this requires to know the length of the array.
Note:
This line of code does what I want
print(*["%f %f"%(a,b) for a,b in zip(x,y)])
but this does use the old formatting style and I would like to know if it's possible with the new one, too. It also looks a little bit funky, I think :-D
Do the following:
x=[1, 2, 3, 4]
y=[5, 6, 7, 8]
result = ' '.join([str(i) for e in zip(x, y) for i in e])
print(result)
Output
1 5 2 6 3 7 4 8
You can use itertools.chain to interleave the elements from both lists:
list(chain.from_iterable(zip(x, y)))
[1, 5, 2, 6, 3, 7, 4, 8]
And if you want to print all elements joined as you specify you can do:
print(*chain.from_iterable(zip(x, y)))
1 5 2 6 3 7 4 8
what about some numpy
np.array(list(zip(a,b))).flatten()
output
array([1, 5, 2, 6, 3, 7, 4, 8])
You can use zip() to iterate through two iterables at the same time.
l1 = [0, 2, 4, 6, 8]
l2 = [1, 3, 5, 7, 9]
for i, j in zip(l1, l2):
print(i)
print(j)
Output:
0
1
2
3
4
5
6
7
8
9
Since you use numpy, what about
>>> ' '.join(np.vstack((x, y)).T.flatten().astype(str))
'1 5 2 6 3 7 4 8'
It's also possible with itertools.starmap:
>>> print(*starmap("{} {}".format, zip(x, y)))
1 5 2 6 3 7 4 8
Normally, the method given by #yatu with itertools.chain is the way to go, especially if you want all elements to be separated by spaces. But starmap could come handy when you'd want to have some special formatting between the pairs, for example:
>>> print(*starmap("{}:{}".format, zip(x, y)))
1:5 2:6 3:7 4:8
Throwing another into the mix
("{} "*len(x)*2).format(*np.ravel(list(zip(x,y))))
'1 5 2 6 3 7 4 8 '

Rearranging numbers from list in python3

Lets say I have an list of numbers
a = [ 1,2,3,4,5,6,7,8,9,10]
and I want to print the output as
1
2 3
4 5 6
7 8 9 10
How can I do it in python3.
My attempt:
a = [1,2,3,4,5,6,7,8,9,10]
for i in a:
print(a[i]," ")
i=i+1
I'm getting IndexError: list index out of range and also I don't know to print 1 element in 1'st row , 2nd and 3rd in second row and so on.
One way to do this in Python 3 is to use islice on an iterator :
from itertools import islice
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
it = iter(a)
print('\n'.join([' '.join([str(u)for u in islice(it, i)])for i in range(1,5)]))
output
1
2 3
4 5 6
7 8 9 10

Categories