How to derive the following pattern with Python - 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]]

Related

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)

Nested loop through list avoiding same element

I can't explain the concept well at all, but I am trying to loop through a list using a nested loop, and I can't figure out how to avoid them using the same element.
list = [1, 2, 2, 4]
for i in list:
for j in list:
print(i, j) # But only if they are not the same element
So the output should be:
1 2
1 2
1 4
2 1
2 2
2 4
2 1
2 2
2 4
4 1
4 2
4 2
Edit as the solutions don't work in all scenarios:
The if i != j solution only works if all elements in the list are different, I clearly chose a poor example, but I meant same element rather than the same number; I have changed the example
You can compare the indices of the two iterations instead:
lst = [1, 2, 2, 4]
for i, a in enumerate(lst):
for j, b in enumerate(lst):
if i != j:
print(a, b)
You can also consider using itertools.permutations for your purpose:
lst = [1, 2, 2, 4]
from itertools import permutations
for i, j in permutations(lst, 2):
print(i, j)
Both would output:
1 2
1 2
1 4
2 1
2 2
2 4
2 1
2 2
2 4
4 1
4 2
4 2
Simply:
if i != j:
print(i, j)

Delete specific Values of an Array: Python

I have an array of the shape (1179648, 909).
The problem is that some rows are filled with 0's only. I am checking for this as follows:
for i in range(spectra1Only.shape[0]):
for j in range(spectra1Only.shape[1]):
if spectra1Only[i,j] == 0:
I now want to remove the whole row of [i] if there is any 0 appearing to get a smaller amount of only the data needed.
My question is: what would be the best method to do so? Remove? Del? numpy.delete? Or any other method?
You can use Boolean indexing with np.any along axis=1:
spectra1Only = spectra1Only[~(spectra1Only == 0).any(1)]
Here's a demonstration:
A = np.random.randint(0, 9, (5, 5))
print(A)
[[5 0 3 3 7]
[3 5 2 4 7]
[6 8 8 1 6]
[7 7 8 1 5]
[8 4 3 0 3]]
print(A[~(A == 0).any(1)])
[[3 5 2 4 7]
[6 8 8 1 6]
[7 7 8 1 5]]

Keeping Python from spacing after breaking a line when printing a List

(yes, I've searched all around for a solution, and, if did I see it, I wasn't able to relate to my issue. I'm new to Python, sorry!)
I've got a work to do, and it says to me:
"User will input X and Y. Show a sequence from 1 to Y, with only X elements each line."
e.g
2 4 as entrance
1 2
3 4
e.g 2 6
1 2
3 4
5 6
Okay... So, I thought on doing this:
line, final = input().split()
line = int(line)
final = int(final)
List = []
i = 0
total = (final // line)
spot = 0
correction = 0
k = 1
if i != final:
List = list(range(1, final + 1, 1))
i += 1
while k != total:
spot = line * k + correction
correction += 1
k += 1
list.insert(List, spot, '\n')
print(*List)
Ok. So I managed to build my List from 1 to the "final" var.
Also managed to find on which spots (therefore, var "spot") my new line would be created. (Had to use a correction var and some math to reach it, but it's 10/10)
So far, so good.
The only problem is this work is supposed to be delivered on URI Online Judge, and it DEMANDS that my result shows like this:
2 10 as entrance
1 2
3 4
5 6
7 8
9 10
And, using the code I just posted, I get this as a result:
1 2
3 4
5 6
7 8
9 10
Thus, it says my code is wrong. I've tried everything to remove those spaces (I think). Using sys won't work since it only prints one argument. Tried using join (but I could have done it wrong, as I'm new anyway)
Well, I've tried pretty much anything. Hope anyone can help me.
Thanks in advance :)
You have built a list that includes each necessary character, including the linefeed. Therefore, you have a list like this:
[1, 2, '\n', 3, 4, '\n'...]
When you unpack arguments to print(), it puts a separator between each argument, defaulting to a space. So, it prints 1, then a space, then 2, then a space, then a linefeed, then a space... And that is why you have a space at the beginning of each line.
Instead of inserting linefeeds into a list, chunk that list with iter and next:
>>> def chunks(x, y):
... i = iter(range(1, y+1))
... for row in range(y//x):
... print(*(next(i) for _ in range(x)))
... t = tuple(i)
... if t:
... print(*t)
...
>>> chunks(2, 6)
1 2
3 4
5 6
>>> chunks(2, 7)
1 2
3 4
5 6
7
The problem with the approach you're using is a result of a space being printed after each "\n" character in the series. While the idea was quite clever, unfortunately, I think this means you will have to take a different approach from inserting the newline character into the list.
Try this approach: (EDITED)
x, y = input().split()
x, y = int(x), int(y)
for i in range(1, y+1):
if i % x == 0 or i == y:
print(i)
else:
print(i, end=" ")
Output for 3 11
1 2 3
4 5 6
7 8 9
10 11
Output for 2 10
1 2
3 4
5 6
7 8
9 10
Use itertools to take from an iterable in chunks:
>>> import itertools
>>> def print_stuff(x,y):
... it = iter(range(1, y + 1))
... chunk = list(itertools.islice(it,X))
... while chunk:
... print(*chunk)
... chunk = list(itertools.islice(it,X))
...
>>> print_stuff(2,4)
1 2
3 4
>>>
And here:
>>> print_stuff(2,10)
1 2
3 4
5 6
7 8
9 10
>>>
I split user input into two string then convert them into int and comapre if y greater than x by 2 because this is minimum for drawing your sequence
Then i make a list from 1 to y
And iterate over it 2 element for each iteration printing them
x,y=input().split()
if int(y)>int(x)+2:
s=range(1,int(y)+1)
for i in range(0,len(s),2):
print(' '.join(str(d) for d in s[i:i+2]))
result:
1 2
3 4
5 6
7 8
9 10

Reverse loop inside a loop with same list

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

Categories