How do I create a magic square matrix using python - python

A basket is given to you in the shape of a matrix. If the size of the matrix is N x N then the range of number of eggs you can put in each slot of the basket is 1 to N2 . You task is to arrange the eggs in the basket such that the sum of each row, column and the diagonal of the matrix remain same
This code is working only for odd numbers but not even numbers.
here's my code that i tried but it didn't work
`
def matrix(n):
m = [[0 for x in range(n)]
for y in range(n)]
i = n / 2
j = n - 1
num = 1
while num <= (n * n):
if i == -1 and j == n:
j = n - 2
i = 0
else:
if j == n:
j = 0
if i < 0:
i = n - 1
if m[int(i)][int(j)]:
j = j - 2
i = i + 1
continue
else:
m[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1
print ("Sum of eggs in each row or column and diagonal ",n * (n * n + 1) / 2, "\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (m[i][j]),end = '')
if j == n - 1:
print()
n=int(input("Number of rows of matrix:"))
matrix(n)
`

def matrix(n):
m = [[0 for x in range(n)]
for y in range(n)]
i = n / 2
j = n - 1
num = 1
while num <= (n * n):
if i == -1 and j == n:
j = n - 2
i = 0
else:
if j == n:
j = 0
if i < 0:
i = n - 1
if m[int(i)][int(j)]:
j = j - 2
i = i + 1
continue
else:
m[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1
print ("Sum of eggs in each row or column and diagonal ",n * (n * n + 1) / 2, "\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (m[i][j]),end = '')
if j == n - 1:
print()
n=int(input("Number of rows of matrix:"))
matrix(n)

def forEvenNumber(n):
arr = [[(n * y) + x + 1 for x in range(n)] for y in range(n)]
for i in range(0, n // 4):
for j in range(0, n // 4):
arr[i][j] = (n * n + 1) - arr[i][j];
for i in range(0, n // 4):
for j in range(3 * (n // 4), n):
arr[i][j] = (n * n + 1) - arr[i][j];
for i in range(3 * (n // 4), n):
for j in range(0, n // 4):
arr[i][j] = (n * n + 1) - arr[i][j];
for i in range(3 * (n // 4), n):
for j in range(3 * (n // 4), n):
arr[i][j] = (n * n + 1) - arr[i][j];
for i in range(n // 4, 3 * (n // 4)):
for j in range(n // 4, 3 * (n // 4)):
arr[i][j] = (n * n + 1) - arr[i][j];
print("\nSum of all row, column and diagonals = ",
n * (n * n + 1) // 2, "\n")
for i in range(n):
for j in range(n):
print('%2d ' % (arr[i][j]), end=" ")
print()
def forOddNumber(n):
mgsqr = [[0 for x in range(n)]
for y in range(n)]
r = n // 2
c = n - 1
num = 1
while num <= (n * n):
if r == -1 and c == n:
c = n - 2
r = 0
else:
if c == n:
c = 0
if r < 0:
r = n - 1
if mgsqr[int(r)][int(c)]:
c = c - 2
r = r + 1
continue
else:
mgsqr[int(r)][int(c)] = num
num = num + 1
c = c + 1
r = r - 1
print("\nSum of all row, column and diagonals = ",
n * (n * n + 1) // 2, "\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (mgsqr[i][j]), end='')
print()
print("\nWELCOME:)\n")
n = int(input("Please Enter Number of Rows and Column (n*n): "))
if n%2==0:
forEvenNumber(n)
else:
forOddNumber(n)
print("\nThank You :)")
This should take in the even inputs and give the right outputs!

Related

Faster prime counting in python

I can't count prime all prime number <= n. My code broken(Execution Timed Out (12000 ms)) on n⩽10**10.
Can anyone help me solve the problem in python?
import numpy as np
def count_primes_less_than(n):
n +=1
assert n >= 6
sieve = np.ones(n // 3 + (n % 6 == 2), dtype=bool)
sieve[0] = False
for i in range(int(n ** 0.5) // 3 + 1):
if sieve[i]:
k = 3 * i + 1 | 1
sieve[((k * k) // 3)::2 * k] = False
sieve[(k * k + 4 * k - 2 * k * (i & 1)) // 3::2 * k] = False
return len(np.r_[((3 * np.nonzero(sieve)[0] + 1) | 1)]) + 2```

How to get all combinations from array python

How to create all possible combinations from the elements of the array of certain length
For instance
N = 6 (length)
arr = ['11'] (mean 11 are adjacent)
Output:
110000
011000
001100
000110
000011
100001
If arr = ['1','1'] (mean, 11 couldn't be adjacent)
N = 6 (length)
Output:
101000
100100
100010
010100
010010
010001
001010
001001
000101
I have the following function, but I don't know how to do the combination to be considered adjacent
100001
Code
def f(arr, N, start=''):
arr1 = arr[1:]
alen = sum(map(len, arr1)) + len(arr1) - 1
if (alen):
alen += 1
for i in range(N - alen - len(arr[0]) + 1):
add = '0' * i + arr[0]
if (arr1):
f(arr1, N - len(add) - 1, start + add + '0')
else:
print(start + add + '0' * (N - len(add)))
arr = ['11']
N = 6
f(arr, N)
please test
check = []
check2 = []
for x in range(5):
arr = [0, 0, 0, 0, 0, 0]
list_of_one_poz = []
arr[x] = 1
for y in range(x, 5):
list_of_one_poz.append(y+1)
for i in list_of_one_poz:
arr[i] = 1
txt = ''.join(str(e) for e in arr)
r_index = txt.rindex('1')
l_index = txt.index('1')
l = list(range(l_index+1, r_index))
for p in l:
arr[p]=0
if r_index - l_index <=1:
check.append(''.join(str(e) for e in arr))
elif r_index - l_index == 5:
check.append(''.join(str(e) for e in arr))
else:
check2.append(''.join(str(e) for e in arr))
print(check)
print("")
print(check2)

Error in my code in python 3 (coin change problem)

This is the error:
Message File Name Line Position
Traceback
34
count 25
TypeError: unsupported operand type(s) for -: 'int' and 'str'
The code can be found here:
import sys
N = int(sys.stdin.readline()) #4
munten = [] #1, 2, 5, 10
for p in range(0, N):
munten.append(sys.stdin.readline())
bedrag = int(sys.stdin.readline()) #13
m = len(munten)
def count(S, m, bedrag):
table = [[0 for x in range(m)] for x in range(bedrag+1)]
for i in range(m):
table[0][i] = 1
for i in range(1, bedrag+1):
for j in range(m):
x = table[i - S[j]][j] if i-S[j] >= 0 else 0
y = table[i][j-1] if j >= 1 else 0
table[i][j] = x + y
return table[bedrag][m-1]
print(count(munten, m, bedrag)) #output = 16
The inputs: N = 4 (amount of coins in array), (the array) munten = (1, 2, 5, 10), (amount to pay) bedrag = 13 --> (amount of combinations I can pay with the coins in the array) output = 16
munten are list of strings in your code.
for p in range(0, N):
munten.append(int(sys.stdin.readline()))
Execution example
> python3 sample.py
> 4 #N
> 1 #munten0
> 2 #munten1
> 5 #munten2
> 10 #munten3
> 13 #bedrag
16

Lucas probable prime test

I have been trying to implement the Baillie-PSW primality test for a few days, and have ran into some problems. Sepcifically when trying to use the Lucas probable prime test. My question is not about Baile, but on how to generate the correct Lucas sequence modulo some number
For the first two psudoprimes my code gives the correct result, eg for 323 and 377. However for the next psudoprime, both the standard implementation and the doubling version fails.
Trying to do modulo operations on V_1 completely breaks the doubling version of the Luckas sequence generator.
Any tips or suggestions on how to correctly implement the Lucas probable prime test in Python?
from fractions import gcd
from math import log
def luckas_sequence_standard(num, D=0):
if D == 0:
D = smallest_D(num)
P = 1
Q = (1-D)/4
V0 = 2
V1 = P
U0 = 0
U1 = 1
for _ in range(num):
U2 = (P*U1 - Q*U0) % num
U1, U0 = U2, U1
V2 = (P*V1 - Q*V0) % num
V1, V0 = V2, V1
return U2%num, V2%num
def luckas_sequence_doubling(num, D=0):
if D == 0:
D = smallest_D(num)
P = 1
Q = (1 - D)/4
V0 = P
U0 = 1
temp_num = num + 1
double = []
while temp_num > 1:
if temp_num % 2 == 0:
double.append(True)
temp_num //= 2
else:
double.append(False)
temp_num += -1
k = 1
double.reverse()
for is_double in double:
if is_double:
U1 = (U0*V0) % num
V1 = V0**2 - 2*Q**k
U0 = U1
V0 = V1
k *= 2
elif not is_double:
U1 = ((P*U0 + V0)/2) % num
V1 = (D*U0 + P*V0)/2
U0 = U1
V0 = V1
k += 1
return U1%num, V1%num
def jacobi(a, m):
if a in [0, 1]:
return a
elif gcd(a, m) != 1:
return 0
elif a == 2:
if m % 8 in [3, 5]:
return -1
elif m % 8 in [1, 7]:
return 1
if a % 2 == 0:
return jacobi(2,m)*jacobi(a/2, m)
elif a >= m or a < 0:
return jacobi(a % m, m)
elif a % 4 == 3 and m % 4 == 3:
return -jacobi(m, a)
return jacobi(m, a)
def smallest_D(num):
D = 5
k = 1
while k > 0 and jacobi(k*D, num) != -1:
D += 2
k *= -1
return k*D
if __name__ == '__main__':
print luckas_sequence_standard(323)
print luckas_sequence_doubling(323)
print
print luckas_sequence_standard(377)
print luckas_sequence_doubling(377)
print
print luckas_sequence_standard(1159)
print luckas_sequence_doubling(1159)
Here is my Lucas pseudoprimality test; you can run it at ideone.com/57Iayq.
# lucas pseudoprimality test
def gcd(a,b): # euclid's algorithm
if b == 0: return a
return gcd(b, a%b)
def jacobi(a, m):
# assumes a an integer and
# m an odd positive integer
a, t = a % m, 1
while a <> 0:
z = -1 if m % 8 in [3,5] else 1
while a % 2 == 0:
a, t = a / 2, t * z
if a%4 == 3 and m%4 == 3: t = -t
a, m = m % a, a
return t if m == 1 else 0
def selfridge(n):
d, s = 5, 1
while True:
ds = d * s
if gcd(ds, n) > 1:
return ds, 0, 0
if jacobi(ds, n) == -1:
return ds, 1, (1 - ds) / 4
d, s = d + 2, s * -1
def lucasPQ(p, q, m, n):
# nth element of lucas sequence with
# parameters p and q (mod m); ignore
# modulus operation when m is zero
def mod(x):
if m == 0: return x
return x % m
def half(x):
if x % 2 == 1: x = x + m
return mod(x / 2)
un, vn, qn = 1, p, q
u = 0 if n % 2 == 0 else 1
v = 2 if n % 2 == 0 else p
k = 1 if n % 2 == 0 else q
n, d = n // 2, p * p - 4 * q
while n > 0:
u2 = mod(un * vn)
v2 = mod(vn * vn - 2 * qn)
q2 = mod(qn * qn)
n2 = n // 2
if n % 2 == 1:
uu = half(u * v2 + u2 * v)
vv = half(v * v2 + d * u * u2)
u, v, k = uu, vv, k * q2
un, vn, qn, n = u2, v2, q2, n2
return u, v, k
def isLucasPseudoprime(n):
d, p, q = selfridge(n)
if p == 0: return n == d
u, v, k = lucasPQ(p, q, n, n+1)
return u == 0
print isLucasPseudoprime(1159)
Note that 1159 is a known Lucas pseudoprime (A217120).

Is this working properly - Sum of Fibonacci in Python 3

I have a task to make a program that will sum the first 100 Fibonacci numbers. I checked my output in Python, and my output in QBasic 64 and they aren't same. I checked with different inputs also.
Input: 10
Output: 89
-----------
Input: 100
Output: 573147844013817084101
Is it correct ?
Here is my code:
n = int(input())
print()
p = 0
d = 1
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
for i in range(n - 2):
p = d
d = z
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
print('Sum:', z)
EDIT: Code edited again, check it now. I just found on Wikipedia.. It depends from what number you start the loop. So if I use (0, 1, 1, 2, 3, 5, 8, 13, 21, and 34) as first 10 Fibonacci numbers, the sum is going to be 88, not 89.
The sums of the first ten and 100 fibonacchi number would be 88 and 573147844013817084100, respectively:
>>> cache = {}
>>> def fib(n):
if n == 0: return 0
if n == 1: return 1
if not n in cache:
cache[n] = fib(n - 1) + fib(n - 2)
return cache[n]
>>> sum([fib(i) for i in range(10)])
88
>>> sum([fib(i) for i in range(100)])
573147844013817084100
In your loop you are already starting the iteration at the 3rd position, since you set. So set your range to (n -2).
0: 1
1 : 1
2 : 1
3 : 2
4 : 3
5 : 5
To get the sum of the Fibonacci numbers, using zero as the first in the series, you need to do this:
def run_it(n):
N2 = 0
N1 = 0
N = 0
z = N
for i in range(n):
print(N,z)
N2 = N1
N1 = N
if N is 0: N = 1
else: N = N1 + N2
z = z + N
run_it(int(input('Number: ')))
To calculate the sum using one as the start of the series, change the initial value of N from zero to one.

Categories