Converting "for loop" to "while loop" in python - python

I am trying to convert the code by replacing for loop with while loop.
This is the code which I want to be converted
Functions for the code in the below snippet. Asked by #Sameer
from random import sample
def shuffle(s): return sample(s,len(s))
rBase = range(base)
base = 2
side = base*base
def pattern(r,c):
return (base*(r%base)+r//base+c)%side
Code in which I have the problem
rows = []
cols = []
data = []
for r in shuffle(rBase):
for g in shuffle(rBase):
rows.append(g*base+r)
for c in shuffle(rBase):
for g in shuffle(rBase):
cols.append(g*base+c)
nums = shuffle(range(1,side+1))
for r in rows:
for c in cols:
data.append(nums[pattern(r,c)])
Here is my attempted code
rows = []
cols = []
data = []
s = shuffle(rBase)
i,j = 0,0
while i < len(s):
r = s[i]
while j < len(s):
s2 = shuffle(rBase)
g = s2[i]
rows.append(g*base+r)
j+=1
i += 1
i,j = 0,0
s = shuffle(rBase)
while i < len(s):
c = s[i]
while j < len(s):
s2 = shuffle(rBase)
g = s2[i]
cols.append(g*base+c)
j += 1
i += 1
nums = shuffle(range(1,side+1))
i,j =0,0
while i < len(rows):
r = rows[i]
while j < len(cols):
c = cols[i]
data.append(nums[pattern(r,c)])
j += 1
i += 1
Some part of the code is omitted due to privacy reasons.
Expected output, ie output of for loop snippet is a list with length (base ** 4) containing each number from 1 to base ** 2 exactly base ** 2 times.
For Eg:
if base is 2:
expected output would be like [3, 2, 1, 4, 4, 1, 3, 2, 1, 4, 2, 3, 2, 3, 4, 1]
Actual output is a list of length base with each element is a random number between 1 and base ** 2.(Including base ** 2)
For Eg:
if base is 2:
Actual output is like [1,1] or [2,2] or [3,3] or [4,4]

Variable j = 0 should be defined before the inner while loop. Currently, your inner while is running 'len(s)' times only also you are indexing with 'i' in your second loop, you should have used j there.
This Should Work
from random import sample
def shuffle(s): return sample(s,len(s))
base = 2
rBase = range(base)
side = base*base
def pattern(r,c):
return (base*(r%base)+r//base+c)%side
rows = []
cols = []
data = []
for r in shuffle(rBase):
for g in shuffle(rBase):
rows.append(g*base+r)
for c in shuffle(rBase):
for g in shuffle(rBase):
cols.append(g*base+c)
print(rows)
print(cols)
nums = shuffle(range(1,side+1))
for r in rows:
for c in cols:
data.append(nums[pattern(r,c)])
print(data)
rows = []
cols = []
data = []
s = shuffle(rBase)
s2 = shuffle(rBase)
i = 0
while i < len(s):
r = s[i]
j = 0
while j < len(s):
g = s2[j]
j = j + 1
rows.append(g*base+r)
i = i + 1
i = 0
s = shuffle(rBase)
s2 = shuffle(rBase)
while i < len(s):
c = s[i]
j = 0
while j < len(s):
g = s2[j]
cols.append(g*base+c)
j += 1
i += 1
nums = shuffle(range(1,side+1))
i =0
while i < len(rows):
r = rows[i]
j = 0
while j < len(cols):
c = cols[j]
data.append(nums[pattern(r,c)])
j += 1
i += 1
print(rows)
print(cols)
print(data)

Related

remove commas , and [ ] from a list python 3

I have a this funtion
n=5
nums=5 1 4 2 3
def LIS(nums, n):
dp = []
dp_list = []
for i in range(n):
dp.append(1)
dp_list.append([nums[i]])
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
if len(dp_list[i]) <= len(dp_list[j]):
dp_list[i] = dp_list[j] + [nums[i]]
print(dp_list[dp.index(max(dp))])
return dp_list
And I get this result:
[1, 2, 3]
But I wan something like this as result
1 2 3
I have tried using this, but the result still been the same
values = ''.join([str(i) for i in LIS(nums,n)])
print(*dp_list[dp.index(max(dp))])

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

Java for loop in Python example

I have in java:
public static void main(String[] args) {
int x = 10;
for(int i = 0; i <= x; i++ ){
System.out.println("i = " + i + "******");
for(int j = 0; j <= i; j++){
System.out.print("j = " + j + " ");
}
}
with output:
run:
i = 0******
j = 0 i = 1******
j = 0 j = 1 i = 2******
j = 0 j = 1 j = 2 i = 3******
j = 0 j = 1 j = 2 j = 3 i = 4******
j = 0 j = 1 j = 2 j = 3 j = 4 i = 5******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 i = 6******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 i = 7******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 i = 8******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 i = 9******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 j = 9 i = 10******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 j = 9 j = 10
I'd like to achieve exactly effect in python for loop:
x = 10
for i in range(0, x, 1):
print("i = ", i, "*******")
for j in range(0, i, 1):
print("j = ", j, end="")
Output:
i = 0 *******
i = 1 *******
j = 0i = 2 *******
j = 0j = 1i = 3 *******
j = 0j = 1j = 2i = 4 *******
j = 0j = 1j = 2j = 3i = 5 *******
j = 0j = 1j = 2j = 3j = 4i = 6 *******
j = 0j = 1j = 2j = 3j = 4j = 5i = 7 *******
j = 0j = 1j = 2j = 3j = 4j = 5j = 6i = 8 *******
j = 0j = 1j = 2j = 3j = 4j = 5j = 6j = 7i = 9 *******
j = 0j = 1j = 2j = 3j = 4j = 5j = 6j = 7j = 8
I started learning python, I know java at intermediate level and cant start thinking in those pyhon loops. Python 3.6
The upper bound of range(..) is exclusive, so you simply need to add one to the upper bound:
x = 10
for i in range(0, x+1):
print("i = ",i,"*******",sep='')
for j in range(0, i+1):
print("j = ",j, sep='', end=' ')
If the step is 1, you do not have to mention this. By default Python uses 1 as step.
Furthermore by default Python will separate two arguments with a space, you can use the sep parameter to split it with no space (or another character sequence).
This prints:
i = 0*******
j = 0 i = 1*******
j = 0 j = 1 i = 2*******
j = 0 j = 1 j = 2 i = 3*******
j = 0 j = 1 j = 2 j = 3 i = 4*******
j = 0 j = 1 j = 2 j = 3 j = 4 i = 5*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 i = 6*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 i = 7*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 i = 8*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 i = 9*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 j = 9 i = 10*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 j = 9 j = 10
You want to use end=" " rather than end="" to have a space between a value of j and the string j = from next iteration.
Besides, the result of range does not include the upper limit, you have to add 1 to compensate for it.
And finally, instead of:
print("i = ", i, "*******")
use
print("i = {}*******".format(i))
to exactly reproduce your Java output.
Simple solution of your problem.
x=10
for i in range(0,x+1):
print "i = "+str(i)+"******"
for j in range(0,i+1):
print "j = "+str(j)+" ",
output:-
i = 0******
j = 0 i = 1******
j = 0 j = 1 i = 2******
j = 0 j = 1 j = 2 i = 3******
j = 0 j = 1 j = 2 j = 3 i = 4******
j = 0 j = 1 j = 2 j = 3 j = 4 i = 5******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 i = 6******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 i = 7******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 i = 8******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 i = 9******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 j = 9 i = 10******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 j = 9 j = 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]]

Appending numbers to emptylist

im trying to return the divisors of 2 numbers that i appended to an empty list. why is nothing being printed? im expecting for 1,2,3 to be returned to mw but i get returned "[]" and "none"
def fun (t,g) :
list1 = []
i = 1
r = 1
while i < t :
if i % t == 0 :
list1.append(i)
i = i + 1
while r < g :
if r % g == 0 :
list1.append(r)
r = r + 1
print list1
x = 4
y = 6
t = fun(x,y)
print t
i % t is never 0 since you are exiting the while loop when i == t. Perhaps you meant t % i?
Likewise for r and g.
Your function doesn't have a return so it will implicitly return None
You should add return list1 to the end of it.
def fun (t,g) :
list1 = []
i = 1
r = 1
while i < t :
if t % i == 0 :
list1.append(i)
i = i + 1
while r < g :
if g % r == 0 :
list1.append(r)
r = r + 1
print list1
return list1
x = 4
y = 6
t = fun(x,y)
print t
prints
[1, 2, 1, 2, 3]
[1, 2, 1, 2, 3]
So you still need to work out the duplicates

Categories

Resources