Creating a Rhombus with numbers in python - python

Create a Rhombus through numbers if i input a number it should print the number of lines as same as input number and print the numbers upto given number, I'm not getting exact solution, Please help me out.
Examples :
If the input is 4
This will be the expected output.
1
1 2 3
1 2 3
1
If the input is 5
This will be the expected output.
1
1 2 3
1 2 3 4 5
1 2 3
1
If the input is 7
This will be the expected output.
1
1 2 3
1 2 3 4 5
1 2 3 4 5 6 7
1 2 3 4 5
1 2 3
1
I have tried,
size = 4
maxlen = len(str(size * size))
m = size * 2 - 1
matrix = [[' ' * maxlen] * m for _ in range(m)]
for n in range(size * size):
r = n // size
c = n % size
matrix[c + r][size - r - 1 + c] = '{0:{1}}'.format(n + 1, maxlen)
print '\n'.join(''.join(row) for row in matrix)
But i'm not getting exact solution. Please help me out..

def pattern_gen(n):
k = n
for i in range(1, n + 1):
if i % 2 != 0:
for j in range(0, int(k/2)):
print(end=" ")
for j in range(1, i+1):
print(j, end="")
print()
k = k - 1
k = 1
if n % 2 != 0:
n = n-1
k = 2
for i in range(n, 0, -1):
if i % 2 != 0:
for j in range(0, int(k/2)):
print(end=" ")
for j in range(1, i+1):
print(j, end="")
print()
k = k + 1

Related

Print nxn grid clockwise and print the sum of the diagonal elements

Example if n = 5 it should print
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
Sum = 21+7+1+3+13+17+5+9+25
= 101
Here is my code
dim=5
result= n = 1
for in range(2,dim,2):
for i in range(4):
n+=k
result+=n
print(result)
Here is what I made
def spiral(n):
# Initialize the values
m = [[0]*n for _ in" "*n] # Define a list of list of n dim
d = n
v = n*n # values
y = 0 # cord of y
x = n # cord of x
while d > 0:
for _ in" "*d: # Equivalent to <=> for i in range(d)
x -= 1
m[y][x] = v
v-=1
d -= 1
for _ in" "*d:
y += 1
m[y][x] = v
v-=1
for _ in" "*d:
x += 1
m[y][x] = v
v-=1
d -= 1
for _ in" "*d:
y -= 1
m[y][x] = v
v-=1
return m # return the list of list
n = 5
matrix = spiral(n)
# Print lines of the matrix
print("Matrix:")
for e in matrix:
print(*e)
# Print the sum
print(f"Sum: {sum(matrix[i][i]for i in range(n)) + sum(matrix[i][n - i - 1]for i in range(n)) - 1}") # There is a - 1 at the end, because the value of the middle is 1
You can rewrite the while loop like this:
while d > 0:
for i in range(4):
for _ in" "*d:
if i%2:
y -= 2 * (i==3) - 1
else:
x -= 2 * (i==0) - 1
m[y][x] = v
v-=1
if i%2 == 0:
d -= 1
It's shorter but less easy to understand
You can compute The Sum this way
def Spiral(size: int):
if(size<=1):
return 1
else:
Sum = 4*(size)**2 - 6(size-1)
return (Sum+Spiral(size-2))
Spiral(5)

how to print for loop output on same line after each iteration

Code
a = int(input("enter a no"))
b = int(input("enter a range"))
for i in range(1, a+1):
print(i)
for j in range(1, b + 1):
c = i * j
print(i, "*", j, "=", c)
Desired output
1 2 3
1 * 1 = 1 2 * 1 = 2 3 * 1 = 3
1 * 2 = 2 2 * 2 = 4 3 * 2 = 6
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27
1 * 10 = 10 2 * 10 = 20 3 * 10 = 30
You can tell print to finish with something other than a newline by specifying the "end" argument:
a = int(input("enter a no "))
b = int(input("enter a range "))
for i in range(1, a+1):
print(i, end=" ")
print("")
for j in range(1, b + 1):
for i in range(1, a+1):
c = i * j
print(i, "*", j, "=", c, end=" ")
print("")
In this case I split the main loop into two separate loops, the first outputs the top line (1, 2, 3...) with some large spacing, whilst the second then does all of the others with slightly less spacing.
I also switched the order of the later loops since there should be b lines, each with a multiplications, so the b loop needs to be the outer (first) loop.
In both cases an empty print statement is used to output a newline when we need it.
This is what you are looking for:
a = int(input("enter a no"))
b = int(input("enter a range"))
for i in range(1, a + 1):
print(i, end="\t"*4)
print("")
for k in range(1, b + 1):
for j in range(1, a + 1):
print(j, "*", k, "=", j*k, end="\t"*2)
print("")
You have to think line-by-line, since you cannot go back in stdout.
The first for will fill the first line
I modified your nested loop because you were using the wrong variables
"\t" is meant to get decent formatting, but it will eventually break if numbers are too big: I believe there is a more refined approach that I am not aware of
print("") is just meant to go to the next line
Approach
Approach is use f-strings to left align all the prints into fields of width 20
Use fixed field widths since otherwise columns won't line up with single and multi-digit numbers
Use print parameter end = '' to avoid carriage returns on after printing a field
Code
a = int(input("enter a no "))
b = int(input("enter a range "))
width = 20
for i in range(1, a+1):
print(f'{i:<{width}}', end="") # Print all multipliers on a single row
print("")
for j in range(1, b + 1):
# Looping over multiplication row
for i in range(1, a+1): # Looping through the columns to multipl
s = f'{i} * {j} = {i*j}' # Expression for column field
print(f'{s:<{width}}', end = '') # Print field left aligned to width 20
print("") # New row
Test
enter a no 4
enter a range 10
1 2 3 4
1 * 1 = 1 2 * 1 = 2 3 * 1 = 3 4 * 1 = 4
1 * 2 = 2 2 * 2 = 4 3 * 2 = 6 4 * 2 = 8
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9 4 * 3 = 12
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36
1 * 10 = 10 2 * 10 = 20 3 * 10 = 30 4 * 10 = 40
I corrected it like this. Thankyou guys.
just add the end="\t"*4 to fix the alignment issue.
a = int(input("enter a no "))
b = int(input("enter a range "))
for i in range(1, a+1):
print(i, end="\t"*4)
print("")
for j in range(1, b + 1):
for i in range(1, a+1):
c = i * j
print(i, "*", j, "=", c, end="\t"*2)
print("")

How to make this run 'faster'? Or is that the right terminology?

I am new to python and I submitted this code for a Hackerrank problem Arrays and Simple Queries, but for a large number of test cases the program is 'terminated due to timeout'. How can I make this more efficient?
I've pasted the main swap function below.
(Repeats M times)
temp = input()
temp = temp.split(" ")
i = int(temp[1])-1
j = int(temp[2])-1
rep = (i-1)+1
if(temp[0]=='1') :
rep = (i-1)+1
while(i<=j) :
count = i-1
ex1 = count
ex2 = i
for k in range(0,rep) :
arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
ex1 = ex1-1
ex2 = ex2-1
i = i+1
else :
rep = (N-(j+1))
while(j>=i) :
count = j+1
ex1 = count
ex2 = j
for k in range(0,rep) :
arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
ex1 = ex1+1
ex2 = ex2+1
j=j-1
Instead of using many loops, you can try simply concatenating slices:
def query(lst, t, start, end):
# Convert to proper zero-indexed index
start -= 1
if t == '1':
return lst[start:end] + lst[:start] + lst[end:]
elif t == '2':
return lst[:start] + lst[end:] + lst[start:end]
# Get the input however you want
N, M = map(int, input().split())
arr = list(map(int, input().split()))
assert len(arr) == N
for _ in range(M):
t, start, end = input().split()
arr = query(arr, t, int(start), int(end))
print(abs(arr[0] - arr[N - 1]))
print(*arr)
Input:
8 4
1 2 3 4 5 6 7 8
1 2 4
2 3 5
1 4 7
2 1 4
Output:
1
2 3 6 5 7 8 4 1

How to insert a newline between different multiplication tables?

I wrote this code to print out the multiplication table from 1 to 9, but it prints it out without a new line between the different tables. Does anyone know how to fix this?
for i in range(1, 10):
for j in range(1, 10):
k = i * j
print(i,"x",j, "=", k)
the result is this:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
Print an empty line between iterations of your for i in range(1, 10): loop, this will separate the tables by the number you're printing the multiplication of
for i in range(1, 4):
for j in range(1, 4):
k = i * j
print(i,"x",j, "=", k)
print()
>> 1 x 1 = 1
>> 1 x 2 = 2
>> 1 x 3 = 3
>> 2 x 1 = 2
>> 2 x 2 = 4
>> 2 x 3 = 6
>> 3 x 1 = 3
>> 3 x 2 = 6
>> 3 x 3 = 9
for i in range(1, 10):
for j in range(1, 10):
k = i * j
print(i,"x",j, "=", k, end='\n')

Kadane's Algorithm for 2D array with known boundaries

I have implemented the Kadane's algorithm for a 2D array in Python 2 with known boundaries, but I'm using the implementation for an online contest and the time it takes is more than the time given.
So that made me think if there is maybe another algorithm similar to Kadane's that has a smaller complexity, or if my code can be optimized in a way. My implementation works for any array with dimensions N x M and a subarray with dimensions maxRows x maxCols.
maxSumSubarray.py
import numpy as np
# returns the maximum sum for the given vector using kadane's algorithm, with
# maxRows maximum members in the sum
def kadane1DwithBounds(maxRows):
global temp
m = s = sum(temp[i] for i in xrange(maxRows))
k = 0
for i in xrange(1, N - maxRows + 1):
s -= temp[k]
s += temp[maxRows + i - 1]
k += 1
m = max(m, s)
return m
# prints the maximum "area" given by the values of an NxM array inside a
# subarray with dimensions maxRows x maxCols. temp holds the latest vector to be
# given to kadane1DwithBounds()
def kadane2DwithBounds(maxRows, maxCols):
global temp
for i in xrange(N):
temp[i] = sum(table[i][j] for j in xrange(maxCols))
m = kadane1DwithBounds(maxRows)
k = 0
for j in xrange(1, M - maxCols + 1):
for i in xrange(N):
temp[i] -= table[i][k]
temp[i] += table[i][maxCols + j - 1]
k += 1
m = max(m, kadane1DwithBounds(maxRows))
print m
line = map(int, raw_input().split())
N = line[0]
M = line[1]
maxRows = line[2]
maxCols = line[3]
table = []
temp = np.empty(N, dtype = int)
for _ in xrange(N):
table.append(map(int, raw_input().split()))
kadane2DwithBounds(maxRows, maxCols)
test.txt
4 8 2 3
1 1 2 3 3 1 1 1
2 2 2 2 2 2 2 2
3 3 3 1 1 3 3 4
0 0 1 1 3 2 2 1
Run with
python maxSumSubarray.py < test.txt
it gives
16
which is correct and is the following rectangle:
2 2 2
3 3 4
I've tried with other dimensions too and I'm pretty sure it works fine. Only problem is time/complexity. Any help would be appreciated! Thanks for your time.

Categories

Resources