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

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)

Related

How to find the largest sequence in binary array?

I'm trying to find the largest 1's secuence inside a random array.
I'm trying to find the longest connection of numbers 1 inside a binary array.
I tried to compare each value of the array with its previous values (i+-1 and j+-1), but I failed.
rows = 5
cols = 5
matrix = np.random.randint(2, size=(rows, cols))
print(matrix)
count = 0
result = 0
for i in matrix:
for j in i:
if j <= cols and j <= len(i):
if j == 1:
count += 1
result = max(result, count)
else:
count = 0
print(result)
This is an example of a random array given in my code
matrix =
[[1 1 0 1 1]
[1 0 0 0 1]
[1 1 1 1 1]
[0 0 1 0 0]
[1 0 1 0 0]]
Once we have found the largest conection of numbers 1, the result will be like that:
matrix =
[[(1) (1) 0 (1) (1)]
[(1) 0 0 0 (1)]
[(1) (1) (1) (1) (1)]
[ 0 0 (1) 0 0]
[ 1 0 (1) 0 0]]
The numbers inside the parentheses, those are the largest conection and the result would be like this:
result = 13
Complete Code
import numpy as np
rows = 200
cols = 200
arr = np.random.rand(rows, cols)
for i in range(len(arr)):
for j in range(len(arr[i])):
if arr[i][j] > 0.4:
arr[i][j] = 1
else:
arr[i][j] = 0
for ii in range(len(arr)):
for jj in range(len(arr[ii])):
if arr[ii][jj] == 1.0 or arr[ii][jj] == 1:
arr[ii][jj] = 1
else:
arr[ii][jj] = 0
arr = arr.astype(int)
print(arr)
dimension = rows * cols
danger = eval("dimension * .0002")
def find_largest(arr):
max_count = 0
visited = set() # coordinates visited by DFS
for y in range(0, len(arr)):
for x in range(0, len(arr[y])):
if arr[y][x] == 1 and (y, x) not in visited:
# Runs DFS search on (y,x) and marks cell as visited
max_count = max(max_count, explore(arr, y, x, visited))
probable_danger = suma(max_count)
print("Quantity of connections: " + str(max_count) +
" ,probability of danger: " + str(probable_danger) + " ,comparing to the total; " +
str(danger))
return max_count
def explore(arr, y, x, visited):
if arr[y][x] == 1 and (y, x) not in visited:
count = 1
visited.add((y, x))
for i, j in adj(arr, y, x):
count += explore(arr, i, j, visited)
return count
else:
return 0
def adj(arr, y, x):
# Generates valid adjacent coordinates for (y, x)
if y - 1 > 0 and arr[y - 1][x] == 1:
yield y - 1, x
if y + 1 < len(arr) and arr[y + 1][x] == 1:
yield y + 1, x
if x - 1 > 0 and arr[y][x - 1] == 1:
yield y, x - 1
if x + 1 < len(arr[y]) and arr[y][x + 1] == 1:
yield y, x + 1
def suma(max_count):
dimension = rows * cols
danger = eval("dimension * .0002")
total_ones = 0
total_zeros = 0
for i in arr:
for j in i:
if j % 2 != 0:
total_ones += 1
else:
total_zeros += 1
found = max_count / total_ones
ones = total_ones/dimension
zeros = total_zeros/dimension
print("Total of 1's "+str(ones) +
" , total of 0's: "+str(zeros))
if (found >= danger):
return found
else:
return 0
find_largest(arr)
You can look at groups of 1s in your matrix as strongly connected components in a graph. You can solve this problem using DFS.
def find_largest(arr):
max_count = 0
visited = set() # coordinates visited by DFS
for y in range(0, len(arr)):
for x in range(0, len(arr[y])):
if arr[y][x] == 1 and (y, x) not in visited:
# Runs DFS search on (y,x) and marks cell as visited
max_count = max(max_count, explore(arr, y, x, visited))
return max_count
Now on DFS itself:
def explore(arr, y, x, visited):
if arr[y][x] == 1 and (y, x) not in visited:
count = 1
visited.add((y, x))
for i, j in adj(arr, y, x):
count += explore(arr, i, j, visited)
return count
else:
return 0
def adj(arr, y, x):
# Generates valid adjacent coordinates for (y, x)
if y - 1 > 0 and arr[y - 1][x] == 1:
yield y - 1, x
if y + 1 < len(arr) and arr[y + 1][x] == 1:
yield y + 1, x
if x - 1 > 0 and arr[y][x - 1] == 1:
yield y, x - 1
if x + 1 < len(arr[y]) and arr[y][x + 1] == 1:
yield y, x + 1

How to convert a number system to decimal system without any interference from another system

I mean how can I convert from any number system to decimal system with get rid of number systems that are inside that system!
This code is an example of a triple system:
notice that the number 001 is not counted in the second counter because it is a binary system!
This code can convert between small systems but cannot convert systems with more than 100 numbers
I tried to make him do it but I failed.
 Who can help me?
def To_decimal(num_str):
dec_num = 0
f = len(num_str)-1
for num in num_str:
dec_num +=int(num)*(3**f)
f-=1
return dec_num
def Find(i,txt):
for v in txt:
if v == i:
return False
return True
def Number_system_of(num):
txt = ""
for i in num:
if Find(i,txt):
txt += i
return len(txt)
t = 0
r=["0","1","2"]
k=[" "," "," "]
x = 0
while x!= 3:
k[0] = r[x]
x+=1
x1 = 0
while x1 != 3:
k[1] = r[x1]
x1+=1
x2 = 0
while x2 != 3:
k[2] = r[x2]
x2+=1
s=""
s = k[0]+k[1]+k[2]
if Number_system_of(s) == 3:
t+=1
print(s,t,To_decimal(s))
out :
000 0 0
001 0 1
002 0 2
010 0 3
011 0 4
012 1 5
020 1 6
021 2 7
022 2 8
100 2 9
101 2 10
102 3 11
110 3 12
111 3 13
112 3 14
120 4 15
121 4 16
122 4 17
200 4 18
201 5 19
202 5 20
210 6 21
211 6 22
212 6 23
220 6 24
221 6 25
222 6 26
this works ! .. but it very slow :<
def Switch(keyl):
key = keyl
L = key[len(key)-1]
R = key[len(key)-2]
key[len(key)-1] = R
key[len(key)-2] = L
return key
def Zero(y,n,f):
keyf = f
for x in range(y,n):
keyf[x]= 0
return keyf
def inkey(ke,r):
for x in ke:
if x == r:
return False
return True
def Getnum(f,li,n):
nl = []
for x in range(0,f):
nl.append(li[x])
i = li[f]
while i != n-1:
i+=1
if inkey(nl,i):
return i
def clear(f,key1,n):
key0 = key1
key0f =[]
for x in range(0,f):
key0f.append(key0[x])
notinkey =[]
for x in range(n):
if inkey(key0f,x):
notinkey.append(x)
key0 = Zero(f,n,key0)
keyl = []
for x in range(len(key0)-len(notinkey)):
keyl.append(key0[x])
for x in notinkey:
keyl.append(x)
return keyl
def plus(kee,f,n,stop):
if kee == stop:
return kee
if f == 0:
kee[0]+=1
kee = clear(1,kee,n)
return kee
if kee[f] == n-1 :
return plus(kee,f-1,n,stop)
k = Getnum(f,kee,n)
if k == None:
return plus(kee,f-1,n,stop)
kee[f]=k
kee = clear(f+1,kee,n)
return kee
def main(n):
key = []
for x in range(n):
key.append(x)
stop = []
for x in range(n-1,-1,-1):
stop.append(x)
o = 1
t = 0
while key != stop :
st = ""
for x in key:
st+=str(x)
print(st,t)
if o == 1 :
key = Switch(key)
if o == 2 :
key = plus(key,n-3,n,stop)
o = 0
t+=1
o+=1
st = ""
for x in stop:
st+=str(x)
print(st,t)
while True:
main(int(input("base ? : ")))

Creating a Rhombus with numbers in 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

Python while loop not breaking

I'm a new programmer and I'm trying to make a rudimentary password generator. But I keep getting this problem where my while loop never breaks.
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = l1.split()
def genpass(n):
x = 0 if x == 0:
password = ''
if n < 100:
while n > x:
password = password + random.choice(l2)
x + 1
print(password)
else:
print 'Sorry, too long'
Can someone tell me what I'm doign wrong? Thanks.
You never change n or x here:
while n > x:
password = password + random.choice(l2)
x + 1
So if the condition was True initially it will always stay True and loop infinitely. Need to do x = x + 1
Incidentally this is the exact sort of bug that Pylint would catch for you.
Please consider the following:
1) Obvious condition
x = 0
if x == 0:
password = ''
You define x = 0, and then checks if x equals 0. It is invariably True.
Hence, you can change it this way:
x = 0
password = ''
2) While loop never ends
Before you had:
while n > x:
[some code]
x + 1 # here was your mistake
Consider these two ways you can add 1 to the variable x:
x = x + 1
or
x += 1
Both mean the same thing.
For further enlightment:
https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements
Can this help? :p
import random
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = list(l1.split())
def genpass(n):
x = 0
password=[]
if n < 100:
while n > x:
password.append(random.choice(l2))
x+=1
return ''.join(password)
else:
return('Sorry, too long')
#example with 14 char
print(genpass(14))
import random
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = l1.split()
def genpass(n):
password = ''
x = 0
if n < 100:
while n > x:
password = password + random.choice(l2)
x = x + 1
print(password)
else:
print 'Sorry, too long'
genpass(10)
You made quite a few errors in your code. What is x+1? It will be x=x+1. Please go through the basics first. Why are you checking if x==0, right after assigning x=0? Don't you think the if will always be yes? Your code in a cleaned format. Hope this works.
import random
l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0'
l2 = l1.split()
def genpass(n):
x = 0
password = ''
if n < 100:
while n > x:
password = password + random.choice(l2)
x=x + 1
print(password)
else:
print ('Sorry, too long')
print("Enter how long you want your password to be")
genpass(int(input()))
You can try this, I've upgraded a little to generate more complex password.
import random
lower = 'q w e r t y u i o p a s d f g h j k l z x c v b n m'
nums = '1 2 3 4 5 6 7 8 9 0'.split()
upper = lower.upper().split()
spcl = '; ! # # & $ '.split()
all = lower.split() + nums + upper + spcl
def genpass(n):
x = 0
if x == 0:
password = ''
if n < 100:
while n > x:
password = password + random.choice(all)
x=x + 1
print(password)
else:
print('Sorry, too long')
# generates a sample password
genpass(10)

Python Nested For Loop Counting Backwards

This is probably a simple problem, but I am trying to created a nested loop that would count up from 0 to 9 in the outer loop, and in the inner loop, start from the value (or index. They are the same in this case) of the outer loop and count backwards.
Here's an example:
i= 0
k= 0
i= 1
k= 1
k= 0
i= 2
k= 2
k= 1
k= 0
i= 3
k= 3
k= 2
k= 1
k= 0
I got this far:
x = range(0,10)
for i in x:
print 'i = ',x[i]
for k in x:
print 'k = ', x[i::-1]
Obviously, the code above doesn't do what I want it to do. For one, the second for loop doesn't start from the value of i in the outer loop and counts backwards. For another, it doesn't print a new k = for every new value.
I think this should be like this:
x = range(0,10)
for i in x:
print 'i = ',x[i]
for k in x[i::-1]:
print 'k = ', k
print("\n")
The result is:
i = 0
k = 0
i = 1
k = 1
k = 0
i = 2
k = 2
k = 1
k = 0
i = 3
k = 3
k = 2
k = 1
k = 0
i = 4
k = 4
k = 3
k = 2
k = 1
k = 0
i = 5
k = 5
k = 4
k = 3
k = 2
k = 1
k = 0
i = 6
k = 6
k = 5
k = 4
k = 3
k = 2
k = 1
k = 0
i = 7
k = 7
k = 6
k = 5
k = 4
k = 3
k = 2
k = 1
k = 0
i = 8
k = 8
k = 7
k = 6
k = 5
k = 4
k = 3
k = 2
k = 1
k = 0
i = 9
k = 9
k = 8
k = 7
k = 6
k = 5
k = 4
k = 3
k = 2
k = 1
k = 0
Basicly, x[i::-1] should be in the for not in the print.
What about just manipulate it with print function?
i = 0
k = 0
while True:
print (i)
print (k)
if 1<k: #tricky part
print ("\n".join([str(h) for h in range(0,k+1)][::-1]))
print ("")
i += 1
k += 1
if i == 10:
break
You are very close. If you are new to the world of python you can take some inspiration from this example where I use list comprehension.
list = lambda k: [ [ i for i in reversed(xrange(j+1)) ] for j in xrange(k+1) ]
Note: If you are using python 3 "xrange" is changed to "range"
Now call:
list(3)
And you'll see that the result is similar to what you are looking for.
[[0], [1, 0], [2, 1, 0], [3, 2, 1, 0]]

Categories

Resources