How to print minimal value from two dimensional array - python

Hello everyone here is my code:
n =[[34,2,55,24,22],[31,22,4,7,333]]
for r in n:
for c in r:
print(c,end = " ")
print()
sums=[]
for i in n:
sum=0
for num in i:
sum+=int(num)
sums.append(sum)
print(*sums)
mini = min([min(r) for r in n])
print(mini)
#This is what it prints out
34 2 55 24 22
31 22 4 7 333
137 397
2
As you can see it prints out smallest number from all array how i can print out smallest number from both rows i have tried using numpy but i have error and then i need to do something to files to fix it which i dont want to do can you please tell me another solution Last thing i need to print it out by changing rows like this and then all other stuff:
31 22 4 7 333
34 2 55 24 22
137 397
4 2

You only need to get the minimum of each row, not the minimum of that.
print(*(min(row) for row in n))

you can use numpy
>>> n = np.array([[34,2,55,24,22],[31,22,4,7,333]])
>>> n.min(axis=1)
array([2, 4])
>>>

Related

Flattening a 2d list into 1d list in python

I have a list of 2D elements
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
and I want my output to be:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20
I tried this loop:
for i in range(3):
for k in range(i,len(m),3):
print(*m[i][k:k+3],sep='\t')
but it prints
1 2 3
4 5
6 7 8
9 10
11 12 13
14 15
16 17 18
and gives me an error
I'm not sure if it is possible since it is going on the next element. Can anyone help me on this?
An approach like this would work:
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
curr = 0
for i in m:
for j in i:
curr += 1
if(curr % 3 == 0):
print(j)
else:
print(j, end = ' ')
Output:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20
You can create a variable, curr, to act as a counter variable. Then, iterate through every element of m, and increment curr with each iteration. For every third element, given by curr % 3 == 0%, we print an element WITH a newline. For every not-third element, we print the element without a newline.
I hope this helped! Please let me know if you have any further questions or clarifications :)
import itertools
x = list(itertools.chain(*m))
print([x[i:i+3] for i in range(0,len(x),3)])
Of course, the above will print the whole thing as a list of lists, but you can go from there to printing each of the individual sublists.
I would try something like
count = 0
for arr in matrix:
for num in arr:
print(num, end=' ')
count += 1
if count == 3:
print()
count = 0
one-line version:
print("".join([str(e)+" " if e%3!=0 else str(e)+"\n" for row in m for e in row]))
P.S. m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]] as that of OP.
easy-to-read version:
m does not need to be identical to that of OP. Could be any 2d matrix.
flat = [e for row in m for e in row]
for i in range(len(flat)):
if i%3 != 2 : print(flat[i], end = " ")
else : print(flat[i], end = "\n")
if len(flat)%3 != 0: print("")
You can use this snippet
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
flag=0
for i in range(len(m)):
for j in range(len(m[i])):
if(flag==3):
print()
flag=0
print(m[i][j],end=" ")
flag+=1
It has multiple ways to do that but easiest way is one line approaching using list comprrehension.
flat = [element for sublist in m for element in sublist]
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
flat = [element for sublist in m for element in sublist]
print("Original list", m)
print("Flattened list", flat)
itertools.chain combines all the sublists, and more_itertools.chunked breaks that up into equal-sized segments.
from itertools import chain
from more_itertools import chunked
m = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]]
for triplet in chunked(chain(*m), 3):
print(*triplet)
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20
(The asterisks are for unpacking; in this case print(*triplet) is effectively the same as print(triplet[0], triplet[1], triplet[2]), and print automatically inserts a space between multiple arguments by default.)
P.S. Nine times out of ten, if you're mucking about with indexes in a Python loop, you don't need to.

Trying to print all my items in a list to rows and columns

So im trying to print the items from the list in to a 18x4 matrix or a table. I´ve tried doing it by using format but it hasn't seem to work.
This is the desired output I want to get from the list, but im not sure how to print the first 18 items in one column and then the next 18 items in second column and so forth. I hope the description is well enough explained since english is not my first language. Any help would be greatly appreciated.
Use nested loops for the rows and columns. In the inner loop, use a stride of 18 to get every 18th element starting from the index in the first column.
for i in range(18):
for j in range(i, len(wireless_node_list), 18):
print(wireless_node_list[j], end='\t')
print()
You'll need to layout each row of output. Figuring out how many rows to display requires some basic math if the goal is to have a target number of columns:
# Some sample data
values = [x / 7 for x in range(50)]
cols = 4
# Figure out how many rows are needed
rows, extra = divmod(len(values), cols)
if extra > 0:
# That means we need one final partial row
rows += 1
# And show each row in turn
for row in range(rows):
line = ""
for col in range(cols):
i = col * rows + row
if i < len(values):
line += f"{i:3d} {values[i]:3.9f} "
print(line)
Which outputs:
0 0.000000000 13 1.857142857 26 3.714285714 39 5.571428571
1 0.142857143 14 2.000000000 27 3.857142857 40 5.714285714
2 0.285714286 15 2.142857143 28 4.000000000 41 5.857142857
3 0.428571429 16 2.285714286 29 4.142857143 42 6.000000000
4 0.571428571 17 2.428571429 30 4.285714286 43 6.142857143
5 0.714285714 18 2.571428571 31 4.428571429 44 6.285714286
6 0.857142857 19 2.714285714 32 4.571428571 45 6.428571429
7 1.000000000 20 2.857142857 33 4.714285714 46 6.571428571
8 1.142857143 21 3.000000000 34 4.857142857 47 6.714285714
9 1.285714286 22 3.142857143 35 5.000000000 48 6.857142857
10 1.428571429 23 3.285714286 36 5.142857143 49 7.000000000
11 1.571428571 24 3.428571429 37 5.285714286
12 1.714285714 25 3.571428571 38 5.428571429
This is a bit brute force, but should work. Just build your list and then do a little math with your indexes.
list = ["112312", "12321312", "9809809", "8374973498", "3827498734", "5426547", "08091280398", "ndfahdda", "ppoiudapp", "dafdsf", "huhidhsaf", "nadsjhfdk", "hdajfhk", "jkhjhkh", "hdjhkajhkj"]
build = {}
len = len(list)
rowCount = len//4 + 1
for i in range(rowCount):
build[i] = []
if i < len: build[i].append(list[i])
if i + 4 < len: build[i].append(list[i + 4])
if i + 8 < len: build[i].append(list[i + 8])
if i + 12 < len: build[i].append(list[i + 12])
print(build)
This little sample tested out fine for me.

Creating a grid of numbers in python using a list

I am trying to write a program that accepts a number , n. The program will print out the numbers n to n+41 as 6 rows of 7 numbers. The first row will contain the values n to n+6, the second , the values n+7 to n+7+6 and so on.
Sample I/O:
Enter the start number: -2
-2 -1 0 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39
The sample I/O looks a little weird on here but I'm sure you can see it.
I understand how to use nested loops to make a triangle but I cannot understand how to print it in a square with the next line have the previous line's value + 1.
Any help would be much appreciated
The first for loop is the key to your problem. It starts at the number entered and goes to that number plus 40 in steps of 6.
starter = int (input ('Enter a number : '))
for x in range (starter, starter + 40, 6) :
for y in range (6) :
print (x + y, end = ' ')
print ()
Before giving you a possible solution, I suggest you carefully read the lots of information about the Python language that there is both on StackOverflow and, in general, on the internet.
You will probably find answers to your questions simply by reading.
This could be one of the methods, if I understand the question correctly, to get the output you want:
# WITHOUT LIST
n = int(input('Enter the start number: '))
printed_values = 0
row_lenght = 7 # values for row
print('\nOUTPUT:\n')
for i in range(n, n+42, 1):
print(i, end='\t')
printed_values += 1
if not printed_values%row_lenght:
#a row is printed, reset printed_values
printed_values = 0
print('\n')
# WITH LIST
n = int(input('Enter the start number: '))
row_lenght = 7 # values for row
values = list(range(n, n+42, 1))
print('\nOUTPUT:\n')
for i in range(0, len(values), row_lenght):
for value in values[i:i+row_lenght]:
print(value, end='\t')
print('\n')

Converting Yes to 1 and No to 0 in python

I have a csv file few columns are as Yes/No's I have tried most of the solutions on stack over flow nothing seems to be working.
sample['colval'] = sample['colval'].apply(lambda x: 0 if x=='N' else 1)
For example, I used the above code on my data. It converted everything to 1's, as in Y to 1 and N to 1.
So many other examples too, all yielded similar results, few resulting in 'None' as output for Y/N.
sample.colval[0:20]
0 N
1 N
2 N
3 N
4 N
5 N
6 N
7 N
8 N
9 N
10 N
11 Y
12 N
13 N
14 N
15 N
16 N
17 N
18 Y
19 N
Name: colval, dtype: object
Please help, Thank you
Found it difficult to repeat given the older version of Python and no access to the original data but your output above suggests whitespace in with the value. Try
sample['colval'] = sample['colval'].apply(lambda x: 0 if x.strip()=='N' else 1)

How do I create a horizontal multiplication table in Python?

So far I have tried to create a table of the first 6 multiples of 2 that should give:
2 4 6 8 10 12
My code for this currently looks like:
i = 1
while i <= 6:
print(2*i ,' \t' , )
i = i + 1
But this outputs them vertically, not horizontally so:
2
4
6
8
10
12
There is also a tab after each number.
You can use a simple for-loop as they are more Pythonic for this application than while loops.
So just loop through the numbers between 1 and 6 and print that number multiplied by 2 with a space instead of the new-line character. Finally, you can call one more print at the end to move to the next line after they have all been printed.
for i in range(1, 7):
print(i * 2, end=' ')
print()
which outputs:
2 4 6 8 10 12
If you wanted do this whole thing in one-line, you could use a generator and string.join(). You may not fully understand this, but the following produces the same result:
print(" ".join(str(i*2) for i in range(1, 7)))
which gives:
2 4 6 8 10 12
Note that one last thing is that this method doesn't produce a uniformly spaced table. To show what I mean by "uniformly spaced", here are some examples:
not uniformly spaced:
1234 1 123 12 12312 123
uniformly spaced:
1234 1 123 12 12312 123
To make the output print nicely like above, we can use .ljust:
print("".join(str(i*2).ljust(3) for i in range(1, 7)))
which gives a nicer table:
2 4 6 8 10 12
Finally, if you wanted to make this into a function that is more general purpose, you could do:
def tbl(num, amnt):
print("".join(str(i*num).rjust(len(str(num*amnt))+1) for i in range(1,amnt+1)))
and some examples of this function:
>>> tbl(3, 10)
3 6 9 12 15 18 21 24 27 30
>>> tbl(9, 5)
9 18 27 36 45
>>> tbl(10, 10)
10 20 30 40 50 60 70 80 90 100
Change your print statement to be like this: print(2*i, end=' \t') The end key argument sets what the ending character should be. By default, it's a newline, as you know.

Categories

Resources