Python. Creating a table from a 2D array with numbered rows - python

t = [[1, 2, 3, 4, 5, 6], [2, 4, 6, 8,
i = 0
a = 0
for i in range(len(t)):
for a in range(len(t[i])):
print(a+1, t[i][a], end=' ')
print('\n', end='')
My expected output would be (in more general terms):
a+1 t[i][a] t[i]+[a+2]...
a+2 t[i+1][a]...
and so on.
For example (with 2D-array t):
1 1 2 3 4 5 6
2 2 4 6 8 10 12
Instead with the above code I get:
1 1 2 2 3 3 4 4 5 5 6 6
1 2 2 4 3 6 4 8 5 10 6 12
And I cannot pinpoint exactly why. Any ideas?

You have a small mistake, as you print a+1 inside the inner loop. You should print i+1 inside the outer loop.
for i, _ in enumerate(t):
print(i+1, end=' ');
for a, _ in enumerate(t[i]):
print(t[i][a], end=' ')
print('\n', end='')

Related

Turn list clockwise for one time

How I can rotate list clockwise one time? I have some temporary solution, but I'm sure there is a better way to do it.
I want to get from this
Index: 0 1 2 3 4 5 6 7 8 9
Count: 0 2 4 4 5 6 6 7 7 7
to this:
Index: 0 1 2 3 4 5 6 7 8 9
Count: 0 0 2 4 4 5 6 6 7 7
And my temporary "solution" is just:
temporary = [0, 2, 4, 4, 5, 6, 6, 7, 7, 7]
test = [None] * len(temporary)
test[0] = temporary[0]
for index in range(1, len(temporary)):
test[index] = temporary[index - 1]
You might use temporary.pop() to discard the last item and temporary.insert(0, 0) to add 0 to the front.
Alternatively in one line:
temporary = [0] + temporary[:-1]

Pyramid fill - how to write input 2 and output [1,1][1,1]

Read an integer nn from standard input and fill the square n×n with integers as follows:
1 2 3 2 1
2 3 4 3 2
3 4 5 4 3
2 3 4 3 2
1 2 3 2 1
or
1 2 2 1
2 3 3 2
2 3 3 2
1 2 2 1
That is, numbers in each column / row increase by one when moving along the column/row towards the center of the matrix.
Implement the matrix as a list of lists of integers, and print the resulting list of lists on standard output.
there is my code, but it cant be output [1,1][1,1],it will be output []
MY CODE:
N = int(input("Enter N value:"))
k = (N) - 1
matrix = [[0 for i in range(k)] for j in range(k)]
for i in range (k):
matrix = []
for j in range (k):
print(matrix)
The code you provided does nothing, I'm assuming that's a copy error on your part.
Anyways, the following should work but bear in mind, that the reversals are not creating deep copies in the following code so if you try to edit the matrix once it is built, it may not behave the way you expect it to.
import math
N = int(input("Enter N value:"))
matrix = []
# iterate over the first math.ceil(N/2) rows
for i in range(math.ceil(N/2)):
matrix.append([])
# create the core numbers
# if i = 0, N = 4, range would be 1,2
# if i = 1, N = 5, range would be 2,3,4
for j in range(i+1, i+1+math.ceil(N/2)):
matrix[i].append(j)
# create copy and reverse it excluding the center element of row
matrix[i] += matrix[i][0:N//2][::-1]
# reverse and append the existing matrix excluding the center row
matrix += matrix[0:N//2][::-1]
print(matrix)
You never populate matrix you are only looping and reassigning matrixto an empty list.
You can use a list comprehension to get the first half, then append it's reverse. You will need some logic to determine what to do if it is even or odd but that's mainly trivial:
n = int(input("Enter N value: "))
half = n // 2
is_odd = n % 2
matrix = [[*range(1 + i, half + i + is_odd+1),
*range(half + i, i, -1)] for i in range(half+is_odd)]
matrix += matrix[:-is_odd or None][::-1]
Result: (formatted as your expected output)
>>> Enter N value: 4
[[1, 2, 2, 1],
[2, 3, 3, 2],
[2, 3, 3, 2],
[1, 2, 2, 1]]
>>> Enter N value: 5
[[1, 2, 3, 2, 1],
[2, 3, 4, 3, 2],
[3, 4, 5, 4, 3],
[2, 3, 4, 3, 2],
[1, 2, 3, 2, 1]]
You can add the intersection of values from an increasing, then decreasing list:
n = 4
R = [(n-abs(i))//2 for i in range(1-n,n,2)] # [0, 1, 1, 0]
M = [ [r+c+1 for c in R] for r in R]
print(*M,sep="\n")
[1, 2, 2, 1]
[2, 3, 3, 2]
[2, 3, 3, 2]
[1, 2, 2, 1]
Visually (looking at R)
r+c+1 for n=4 r+c+1 for n=5
R | 0 1 1 0 R | 0 1 2 1 0
----------- -------------
0 | 1 2 2 1 0 | 1 2 3 2 1
1 | 2 3 3 2 1 | 2 3 4 3 2
1 | 2 3 3 2 2 | 3 4 5 4 3
0 | 1 2 2 1 1 | 2 3 4 3 2
0 | 1 2 3 2 1
You could also combine this in a single list comprehension:
M = [[n-(abs(r)+abs(c))//2 for c in range(1-n,n,2)] for r in range(1-n,n,2)]
or in a more basic for-loop:
for r in range(1-n,n,2): # r\c | -3 -1 1 3
for c in range(1-n,n,2): # -3 | 1 2 2 1
print(n-(abs(r)+abs(c))//2,end=" ") # -1 | 2 3 3 2
print() # 1 | 2 3 3 2
# 3 | 1 2 2 1

numpy.random.randint does not return a list separte by comma

I am running this code:
import numpy as np
Z=np.ones(10)
I = np.random.randint(0,len(Z),20).
print I
#[9 0 0 1 0 2 3 4 3 3 2 2 7 8 1 9 9 2 1 7]
#so this instruction does not work
print Z[I]
return a list without where the elelements does not separates by comma as mentioned here randint
The output on that page shows the interpreter (or repr) output. Also, I changed it to randint and removed the period that would have thrown a syntax error.
import numpy as np
I = np.random.randint(0, 10, 10)
print(I) # => [9 4 2 7 6 3 4 5 6 2]
print(repr(I)) # => array([9, 4, 2, 7, 6, 3, 4, 5, 6, 2])
print(type(I)) # => <type 'numpy.ndarray'>
L = list(I)
print(L) # => [9, 4, 2, 7, 6, 3, 4, 5, 6, 2]
Changing the randomint to randint works for me:
Z=np.arange(10)
I = np.random.randint(0,len(Z),20)
print I
#[9 0 0 1 0 2 3 4 3 3 2 2 7 8 1 9 9 2 1 7]
#so this instruction works for me
print Z[I]
# [3 9 6 6 7 7 7 3 7 5 5 2 1 1 5 7 1 0 7 4]

range() function is giving me trouble

If I were to type something like this, I would get these values:
print range(1,10)
[1,2,3,4,5,6,7,8,9]
but say if I want to use this same value in a for loop then it would instead start at 0, an example of what I mean:
for r in range(1,10):
for c in range(r):
print c,
print ""
The Output is this:
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
Why is 0 here? shouldn't it start at 1 and end in 9?
You are creating a second range() object in your loop. The default start value is 0.
Each iteration you create a loop over range(r), meaning range from 0 to r, exclusive, to produce the output numbers. For range(1) that means you get a list with just [0] in it, for range(1) you get [0, 1], etc.
If you wanted to produce ranges from 1 to r inclusive`, just add 1 to the number you actually print:
for r in range(1,10):
for c in range(r):
print c + 1,
print ""
or range from 1 to r + 1:
for r in range(1,10):
for c in range(1, r + 1):
print c,
print ""
Both produce your expected output:
>>> for r in range(1,10):
... for c in range(r):
... print c + 1,
... print ""
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
>>> for r in range(1,10):
... for c in range(1, r + 1):
... print c,
... print ""
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
If you pass only one argument to range function, it would treat that as the ending value (without including it), starting from zero.
If you pass two arguments to the range function, it would treat the first value as the starting value and the second value as the ending value (without including it).
If you pass three arguments to the range function, it would treat the first value as the starting value and the second value as the ending value (without including it) and the third value as the step value.
You can confirm this with few trial runs like this
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Default start value 0
>>> range(5, 10)
[5, 6, 7, 8, 9] # Starts from 5
>>> range(5, 10, 2)
[5, 7, 9] # Starts from 5 & takes only the 2nd element
Nope.
for r in range(1,10):
for c in range(r):
print c,
print ""
range(), when only given one argument, prints the numbers from 0 to the argument, not including the argument:
>>> range(6)
[0, 1, 2, 3, 4, 5]
And so, on the third iteration of your code, this is what happens:
for r in range(1,10): # r is 3
for c in range(r): # range(3) is [0,1,2]
print c, #you then print each of the range(3), giving the output you observe
print ""
https://docs.python.org/2/library/functions.html#range
From the docs:
The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0.

Unknown number of iterations to complete the sort

I am heading towards sorting algorithms. I have just started to learn the Insertion Sort. I needed to make a solution for a already sorted list with an unsorted number at the end. So the problem now is that the loop skips one iteration or adds another duplicate one. Here is what I mean:
When I try to sort this list: {2, 4, 6, 8 ,3} I get this:
2 4 6 8 3
2 4 6 8 8
2 4 6 6 8
2 4 4 6 8
2 3 4 6 8
2 3 4 6 8 #duplicated! ^
And when I try to sort this list: {2, 4, 6, 8, 1} I get this:
2 4 6 8 8
2 4 6 6 8
2 4 4 6 8
2 2 4 6 8
1 2 4 6 8 #no duplicates
How can I know how many iteration do I need to complete the sort? Here's how I sort:
ar = list(map(int, input().split()))
mins = ar[-1]
for i in range(len(ar)-1, 0, -1):
if ar[i-1] > mins: ar[i] = ar[i-1]
else: ar[i] = mins
print(*ar)
if mins < ar[0]: ar[0] = mins
print(*ar)
Simply break the loop when you find a[i-1] <= mins.
ar = [2, 4, 6, 8 ,1]
mins = ar[-1]
for i in range(len(ar)-1, 0, -1):
if ar[i-1] > mins:
ar[i] = ar[i-1]
else:
ar[i] = mins
break
print(ar)
if mins < ar[0]: ar[0] = mins
print(ar)

Categories

Resources