Need numbering above each column of a python grid - python-3.5

I need to modify a program the program 'x' so that it outputs the original grid, but each row and column is labeled with it's respective number. i.e. column 1 has a first, row 1 has a 1 first. I have figured out how to put numbering in front of the rows, but cannot figure out how to modify the program so that the columns are numbered.
'x'
import random
aGrid = []
SIZE = 10
for r in range (0,SIZE,1):
aGrid.append ([])
for c in range (0,SIZE,1):
element = random.randint(0,9)
aGrid[r].append (element)
for r in range (0,SIZE,1):
for c in range (0,SIZE,1):
print(aGrid[r][c], end="")
print()
Here is my attempt at getting numbering in front of the rows
import random
aGrid = []
SIZE = 11
for r in range (0,SIZE - 1,1):
aGrid.append ([])
aGrid[r].append (r )
aGrid[r].append (" ")
for c in range (0,SIZE + 1,1):
element = random.randint(0,9)
aGrid[r].append (element)
for r in range (0,SIZE - 1,1):
for c in range (0,SIZE + 1,1):
print(aGrid[r][c], end="")
print()

You don't need to change aGrid. Just print the row and column numbers in the print loop:
import random
aGrid = []
SIZE = 10
for r in range (SIZE):
aGrid.append ([])
for c in range (SIZE):
element = random.randint(0,9)
aGrid[r].append (element)
print(" ", end="")
for c in range (SIZE):
print(c, end="")
print()
for i, r in enumerate(range(SIZE)):
print(i, end="")
for c in range(SIZE):
print(aGrid[r][c], end="")
print()
Output:
0123456789
01958724133
17006217440
21488953544
35615572045
49849348546
54207744418
63316678723
76651582077
85713263320
91939404287
A version that starts counting from 1 and has some spaces for better readability:
import random
aGrid = []
SIZE = 10
for r in range (SIZE):
aGrid.append ([])
for c in range (SIZE):
element = random.randint(0,9)
aGrid[r].append (element)
print(" ", end=" ")
for c in range (1, SIZE + 1):
print(c, end=" ")
print()
for i, r in enumerate(range(SIZE), 1):
print('{:2d}'.format(i), end=" ")
for c in range(SIZE):
print(aGrid[r][c], end=" ")
print()
Output:
1 2 3 4 5 6 7 8 9 10
1 3 0 4 6 3 9 3 3 6 3
2 5 6 1 6 6 3 2 5 6 1
3 6 9 0 5 0 7 1 1 7 7
4 7 4 3 9 0 9 1 0 7 8
5 5 1 1 1 1 7 1 4 4 8
6 4 5 8 1 6 3 6 2 8 6
7 4 1 0 5 7 4 5 6 6 4
8 4 5 5 4 3 3 0 9 2 1
9 3 6 7 0 0 9 5 8 5 9
10 3 1 2 3 5 0 1 6 2 9

Related

Tracing sorting algorithms

I am trying to trace the changes in selection sort algorithm with python, Here's a piece of my code and what I've tried, the problem I am facing is printing the results in a table-like format
l = [2,5,1,7,9,5,3,0,-1]
iterat = 1
print('Iteration' + '\t\t\t' + 'Results')
for i in range(1, len(l)):
val_to_sort = l[i]
while l[i-1] > val_to_sort and i > 0:
l[i-1], l[i] = l[i], l[i-1]
i -= 1
print(iterat, '\t\t\t', l[0:iterat + 1],'|',l[iterat:])
iten += 1
from the code above, I am obtaining the following results:
But I am trying to obtain such results
Unident print one level to the left, so it is inside the for block instead of the while block.
Use join and map to print the lists as a string
You can use enumerate instead of manually incrementing iterat
def format_list(l):
return ' '.join(map(str, l))
l = [2,5,1,7,9,5,3,0,-1]
print('Iteration' + '\t\t\t' + 'Results')
for iterat, i in enumerate(range(1, len(l)), 1):
val_to_sort = l[i]
while l[i-1] > val_to_sort and i > 0:
l[i-1], l[i] = l[i], l[i-1]
i -= 1
print(iterat, '\t\t\t', format_list(l[0:iterat + 1]),'|', format_list(l[iterat:]))
Outputs
Iteration Results
1 2 5 | 5 1 7 9 5 3 0 -1
2 1 2 5 | 5 7 9 5 3 0 -1
3 1 2 5 7 | 7 9 5 3 0 -1
4 1 2 5 7 9 | 9 5 3 0 -1
5 1 2 5 5 7 9 | 9 3 0 -1
6 1 2 3 5 5 7 9 | 9 0 -1
7 0 1 2 3 5 5 7 9 | 9 -1
8 -1 0 1 2 3 5 5 7 9 | 9
I can't help you with the Cyrillic text though ;)

if values existes from given list in multiple column and counts the number of column

i have below df
B C D E
2 2 4 11
11 0 5 3
12 10 1 11
5 9 7 15
1st i wants a unique value from whole df like below:
[0,1,2,3,4,5,7,9,10,11,12,15]
then i wants final output
value value exists in number of col
0 1
1 1
2 2
3 1
4 1
5 1
7 1
9 1
10 1
11 2
12 1
15 1
that means each value,how many columns its available
i wants that output
Using python you can do something like this:
# your input df as a list of lists
df = [[2,11,12,5], [2,0,10,9], [4,5,1,7], [11,3,11,15]]
#remove duplicates in each list
dfU = [list(set(l)) for l in df]
# sort each list (not required for this approach)
for l in dfU:
l.sort()
# the requested unique list
flatList = [item for sublist in df for item in sublist]
uniqueList = list(set(flatList))
print(uniqueList)
# output as a list of lists
output = []
for num in uniqueList:
cnt = 0
for idx in range(len(dfU)):
if dfU[idx].count(num) > 0:
cnt+=1
output.append([num,cnt])
print(output)
Side note, the count function is computationally expensive, so it would be better to do a linear scan along all sorted columns.
Use DataFrame.melt for reshape, remove duplicates by both columns and count by GroupBy.size with Series.reset_index for DataFrame:
df1 = (df.melt(value_name='value')
.drop_duplicates()
.groupby('value')
.size()
.reset_index(name='count'))
print (df1)
value count
0 0 1
1 1 1
2 2 2
3 3 1
4 4 1
5 5 2
6 7 1
7 9 1
8 10 1
9 11 2
10 12 1
11 15 1
Details:
print (df.melt(value_name='value'))
variable value
0 B 2
1 B 11
2 B 12
3 B 5
4 C 2
5 C 0
6 C 10
7 C 9
8 D 4
9 D 5
10 D 1
11 D 7
12 E 11
13 E 3
14 E 11
15 E 15
One 11 for index 14 is removed:
print (df.melt(value_name='value').drop_duplicates())
variable value
0 B 2
1 B 11
2 B 12
3 B 5
4 C 2
5 C 0
6 C 10
7 C 9
8 D 4
9 D 5
10 D 1
11 D 7
12 E 11
13 E 3
15 E 15
If want pure python solution:
from collections import Counter
L = sorted(Counter([y for x in df.T.values for y in set(x)]).items())
df1 = pd.DataFrame(L, columns=['value','count'])
print (df1)
value count
0 0 1
1 1 1
2 2 2
3 3 1
4 4 1
5 5 2
6 7 1
7 9 1
8 10 1
9 11 2
10 12 1
11 15 1

how to store python console output in python variable

below is my code :
def combinationUtil(arr, n, r,index, data, i):
if(index == r):
for j in range(r):
print(data[j], end = " ")
print(" ")
return
if(i >= n):
return
data[index] = arr[i]
combinationUtil(arr, n, r, index + 1, data, i + 1)
combinationUtil(arr, n, r, index, data, i + 1)
def printcombination(arr, n, r):
data = list(range(r))
combinationUtil(arr, n, r, 0, data, 0)
var = []
pp = 5
r = 3
arr = []
for i in range(1, pp+1):
arr.append(i)
n = len(arr)
printcombination(arr, n, r)
it gives me this output:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
i want to save this output as a variable in python
You have a combination utility routine that produces the output of interest.
If you were calling someone else's routine, you might need to assign
sys.stdout to an io.StringIO() to capture the output.
But as it stands, you have control over the source code,
so you can easily replace
for j in range(r):
print(data[j], end=' ')
print(' ')
with the following more convenient interface:
yield [data[j] for j in range(r)]
Then iterate, e.g.:
for row in combinationUtil(arr, n, r, 0, list(range(r)), 0):
print(row)
Cf itertools.

Python how to print 1D list as 2D

I want to print a list [1,2,3,4,5,6,7,8,9] as
1 2 3
4 5 6
7 8 9
Here is my code
for i,j in enumerate(list):
if i is not 0 and i % 3==0:
print()
else:
print(j,end=" ")
My result is
1 2 3
5 6
8 9
Can someone help explain why this happen and give me some advise?
You should print the list item j unconditionally instead of doing it only when you are not printing a newline:
l = [1,2,3,4,5,6,7,8,9]
for i,j in enumerate(l):
if i is not 0 and i % 3==0:
print()
print(j,end=" ")
You can do:
tgt=[1,2,3,4,5,6,7,8,9]
n=3
print('\n'.join([' '.join(map(str, sl)) for sl in [tgt[i:i+n] for i in range(0,len(tgt),n)]]))
Prints:
1 2 3
4 5 6
7 8 9

How to sum columns in pandas and add the result into a new row?

In this code I want to sum each column and add it as a new row.
It does the sum but it does not show the new row.
df = pd.DataFrame(g, columns=('AWA', 'REM', 'S1', 'S2'))
df['xSujeto'] = df.sum(axis=1)
xEstado = df.sum(axis=0)
df.append(xEstado, ignore_index=True)
df
I think you can use loc:
df = pd.DataFrame({'AWA':[1,2,3],
'REM':[4,5,6],
'S1':[7,8,9],
'S2':[1,3,5]})
#add 1 to last index value
print (df.index[-1] + 1)
3
df.loc[df.index[-1] + 1] = df.sum()
print (df)
AWA REM S1 S2
0 1 4 7 1
1 2 5 8 3
2 3 6 9 5
3 6 15 24 9
Or append from comment of Nickil Maveli:
xEstado = df.sum()
df = df.append(xEstado, ignore_index=True)
print (df)
AWA REM S1 S2
0 1 4 7 1
1 2 5 8 3
2 3 6 9 5
3 6 15 24 9

Resources