From 8c5778982f6b0f493752aff8b4b4892729d20072 Mon Sep 17 00:00:00 2001 From: bhuvanakundumani Date: Wed, 24 Oct 2018 14:44:11 +0530 Subject: [PATCH 1/2] Added the magic square algorithm --- math/magic_square.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 math/magic_square.py diff --git a/math/magic_square.py b/math/magic_square.py new file mode 100644 index 0000000..dca9adf --- /dev/null +++ b/math/magic_square.py @@ -0,0 +1,42 @@ + + + +"""A magic square is an N×N grid of numbers in which the entries in each row, column and main diagonal sum to the same number (equal to N(N2+1)/2)""" + + +import numpy as np + + +print("Hi! Welcome to the magic square algorithm") +print("Please enter the number for which you would want a magic sqaure to be printed. Please enter an odd number") + +# The odd number for which the magic square is created is stored in the variable N + +N = int(input()) + +# create a matrix with values 0 using numpy. The datatype is int for the elements in the matrix +magic_square = np.zeros((N,N), dtype=int) + +n = 1 +i, j = 0, N//2 + +# n iterates from 1 to N**2. The loop exits when n is equal to N**2 + +while n <= N**2: + # Start in the middle of the first row. + # (i = 0 and j = N//2 ) and the element at magic_square[i,j] is the middle in the first row. + # insert n = 1 to begin with at magic_square[i,j] + magic_square[i, j] = n + # increment n by 1 + n += 1 + # Move diagonally up and right, wrapping to the first column or last row if the move leads outside the grid + + new_i, new_j = (i-1) % N, (j+1)% N + + # if the cell is already filled with a number, move vertically down one space. + if magic_square[new_i, new_j]: + i += 1 + else: + i, j = new_i, new_j + +print(magic_square) From 5806a45a5cb66048d766cf2958f5acc782b26137 Mon Sep 17 00:00:00 2001 From: bhuvanakundumani Date: Wed, 24 Oct 2018 15:19:17 +0530 Subject: [PATCH 2/2] Pascla's Traingle implemented --- math/pascals_triangle.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 math/pascals_triangle.py diff --git a/math/pascals_triangle.py b/math/pascals_triangle.py new file mode 100644 index 0000000..ea625d4 --- /dev/null +++ b/math/pascals_triangle.py @@ -0,0 +1,26 @@ + +""" +Pascal's triangle is a triangular array of numbers in which those at the ends of the rows are 1 and each of the others is the sum of the nearest two numbers in the row above (the apex, 1, being at the top). + +""" +print("Welcome to Pascal's traingle:") + + +n=int(input("Enter number of rows for the pascal's traingle: ")) +a=[] +for i in range(n): + a.append([]) + a[i].append(1) + for j in range(1,i): + a[i].append(a[i-1][j-1]+a[i-1][j]) + if(n!=0): + a[i].append(1) + + +# printing pascal's triangle +print( " Your Pascal's traiange for the number {}".format(n)) +for i in range(n): + print(" "*(n-i),end=" ",sep=" ") + for j in range(0,i+1): + print('{0:6}'.format(a[i][j]),end=" ",sep=" ") + print()