Python matrix is resetting outside of function - python

I'm trying to build a system to randomly generate ship positions for a basic battleship game. To represent the grid I'm using nested list. However once the function has finished the matrix appears to revert back to what it was before I ran the function.
As you can see by running this code, the whole matrix works as intended when printed within the function but afterwards not. It's my first program I've tried building on my own and I've never gotten stuck for this long before. Thanks
import random
row, column = 10, 10;
Matrix = [[0 for x in range(row)] for y in range(column)]
ships = {'battleship':5, 'cruiser':4,'destroyer':3}
any_left = 1
def position_ship(type):
row, column = 10, 10;
Matrix = [[0 for x in range(row)] for y in range(column)]
ship_size_to_assign = type
start_pointV = 5 ### random.randint(0,10)
start_pointH = 5 ### random.randint(0,10)
start_point_direction = 1 ###random.randint(0,4)
print start_pointV
print start_pointH
print start_point_direction
start_point_direction = 1
if start_point_direction == 1:
n = 0
if (start_pointV + type) <= 10:
while ship_size_to_assign != 0:
Matrix[(start_pointH-1)][(start_pointV+n-1)] = 1
print "----------"
print Matrix[(start_pointH-1)][(start_pointV+n-1)]
print "----"
n = n + 1
ship_size_to_assign = ship_size_to_assign - 1
if start_point_direction == 2:
print "/////"
n = 0
if (start_pointH + type) <= 10:
while ship_size_to_assign != 0:
Matrix[start_pointH+n-1][start_pointV-1] = 1
n = n + 1
ship_size_to_assign = ship_size_to_assign - 1
if start_point_direction == 3:
print "/////"
n = 0
if (start_pointV - type) > 0:
while ship_size_to_assign != 0:
Matrix[start_pointH-1][start_pointV-n-1] = 1
n = n + 1
ship_size_to_assign = ship_size_to_assign - 1
if start_point_direction == 4:
print "/////"
n = 0
if (start_pointH - type) > 0:
while ship_size_to_assign != 0:
Matrix[start_pointH-1][start_pointV+n-1] = 1
n = n + 1
ship_size_to_assign = ship_size_to_assign - 1
print "####"
print Matrix[0]
print Matrix[1]
print Matrix[2]
print Matrix[3]
print Matrix[4]
print Matrix[5]
print Matrix[6]
print Matrix[7]
print Matrix[8]
print Matrix[9]
position_ship(5)
print "/////"
print Matrix[0]
print Matrix[1]
print Matrix[2]
print Matrix[3]
print Matrix[4]
print Matrix[5]
print Matrix[6]
print Matrix[7]
print Matrix[8]
print Matrix[9]

Related

Finding common outputs of 3 functions

I have 3 functions.These are
A(n) = n(n+1)/2
B(n) = n(3n-1)/2
C(n) = n(2n-1)
Their first common output and indexes are:
A(285)=B(165)=C(143)=40755
I need second one,so I tried this:
def equation1(x):
return x*(x+1)/2
def equation2(x):
return x*((3*x)-1)/2
def equation3(x):
return x*((2*x)-1)
for i in range(144,30000):
x = equation3(i)
for a in range(i,2*i):
y = equation2(a)
if(x==y):
for b in range(a,2*a):
z = equation1(b)
if(x==y==z):
print("Term =" + str(x))
print("A" + str(b))
print("B" + str(a))
print("C" + str(i))
But it takes too much time to find it.How can I handle this in an easier way?
Since all three functions are increasing for positive values, you can write a loop that increases the number with the smallest value at each iteration:
a = b = c = 1
eq_a = equation1(a)
eq_b = equation2(b)
eq_c = equation3(c)
while True:
if eq_a == eq_b and eq_b == eq_c:
print("Found {}, {}, {}, result={}".format(a,b,c,eq_a))
if eq_a <= eq_b and eq_a <= eq_c:
a += 1
eq_a = equation1(a)
elif eq_b <= eq_a and eq_b <= eq_c:
b += 1
eq_b = equation2(b)
elif eq_c <= eq_a and eq_c <= eq_b:
c += 1
eq_c = equation3(c)
else:
print("Should never be here")
assert(False);
Test run:
Found 1, 1, 1, result=1
Found 285, 165, 143, result=40755
Found 55385, 31977, 27693, result=1533776805
Found 10744501, 6203341, 5372251, result=57722156241751

What is wrong with my nested while loop for counting the element

I just want to figure out how often each element of F occurs within N and print it out. I have used the nested for loop, it works. But when I used nested while loop, it did not work as expected. I checked my code but cannot find out why.
F = [4,7,2]
N = [2,3,4,2,5,6,3,2,6,7,3,4]
Nested for loop version, works as expected:
four_count = 0
seven_count = 0
two_count = 0
for n in N:
for f in F:
if n == f and f == 4:
four_count += 1
elif n == f and f == 7:
seven_count += 1
elif n == f and f == 2:
two_count += 1
print(str(F[0]) + " occurs in N " + str(four_count) + " times")
print(str(F[1]) + " occurs in N " + str(seven_count) + " times")
print(str(F[2]) + " occurs in N " + str(two_count) + " times")
This is correct output:
4 occurs in N 2 times
7 occurs in N 1 times
2 occurs in N 3 times
Nested while loop version, wrong output:
four_count = 0
seven_count = 0
two_count = 0
N_Count = 0
F_Count = 0
while N_Count < len(N):
while F_Count < len(F):
if N[N_Count] == F[F_Count] and F[F_Count] == 4:
four_count += 1
elif N[N_Count] == F[F_Count] and F[F_Count] == 7:
seven_count += 1
elif N[N_Count] == F[F_Count] and F[F_Count] == 2:
two_count += 1
F_Count += 1
N_Count += 1
print(str(F[0]) + " occurs in N " + str(four_count) + " times")
print(str(F[1]) + " occurs in N " + str(seven_count) + " times")
print(str(F[2]) + " occurs in N " + str(two_count) + " times")
Wrong output from nested while loop:
4 occurs in N 0 times
7 occurs in N 0 times
2 occurs in N 1 times
You have to reset F_Count = 0 after while N_Count < len(N):, otherwise list F is only looped once. So it would be:
...
while N_Count < len(N):
F_Count = 0
while F_Count < len(F):
...
But unless you're learning about loops, this would not be the best way to do what you want. Something using count would be better, like:
counts = [N.count(f) for f in F]
or similar

How to return properly?

I am having trouble returning the answer properly.
Is the return roll_dice(x) syntax correct, or do I need to replace x with something else in the parentheses?
I am a beginner and would like some help with this problem:
My code:
import numpy as np
def roll_dice(x):
totmoney = 0
for a in range(x):
throw_one = np.random.randint(6)
throw_two = np.random.randint(6)
if throw_one % 2 != 0 or throw_two % 2 != 0:
totmoney += throw_one + throw_two
print throw_one,"|",throw_two,"|",totmoney
else:
totmoney -= throw_one + throw_two
print throw_one,"|",throw_two,"|",totmoney
return roll_dice(x)
Without doing too much modifications, I think what you wanted to do is:
import random
def roll_dice(x):
totmoney = 0
result_matrix = []
for a in range(x):
throw_one = random.randint(1, 6)
throw_two = random.randint(1, 6)
if throw_one % 2 != 0 or throw_two % 2 != 0:
totmoney += throw_one + throw_two
print throw_one,"|",throw_two,"|",totmoney
else:
totmoney -= throw_one + throw_two
print throw_one,"|",throw_two,"|",totmoney
result_matrix.append([throw_one, throw_two, totmoney])
return result_matrix
example = roll_dice(2)
print example
(I have used the random module because I don't have numpy installed)
You create the matrix one row at a time each time you go through the loop and at the end this matrix is what you return.
But I would add some additional modifications:
import random
def roll_dice(x):
totmoney = 0
result_matrix = []
for a in range(x):
throws = [random.randint(1, 6), random.randint(1, 6)]
if throws[0] % 2 != 0 or throws[1] % 2 != 0:
totmoney += sum(throws)
else:
totmoney -= sum(throws)
print throws[0],"|",throws[1],"|",totmoney
result_matrix.append([throws[0], throws[1], totmoney])
return result_matrix
example = roll_dice(2)
print example
Here's what I have put in place:
I have put your two throws into a list named throws
I have used the sum function to add these two throws
I have put your print statement outside of your if statement
We could go much further, but I'm getting tired and I don't want to confuse you with more advanced stuff.

string indices must be integers Battle ships codewars kata

Im getting this error when inputting my code in codewars. "Traceback:in module
in damaged_or_sunk
IndexError: list index out of range". However, when I try my code in spyder3, it works just fine. there are no indicators as to where this error is in the function damaged_or_sunk though.
def damaged_or_sunk (board, attacks):
a = sum(x.count(1) for x in board)
b = sum(x.count(2) for x in board)
c = sum(x.count(3) for x in board)
a1 = 0
b1 = 0
c1 = 0
points = 0
sunk = 0
damaged = 0
not_touched = 0
for each in attacks:
rand_row = each[0]
rand_col = each[1]
if board[rand_row][rand_col] == 1:
a1 += 1
elif board[rand_row][rand_col] == 2:
b1 += 1
elif board[rand_row][rand_col] == 3:
c1 += 1
else:
pass
if a1 == a:
points += 1
sunk += 1
elif a1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
if b1 == b:
points += 1
sunk += 1
elif b1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
if c1 == c:
points += 1
sunk += 1
elif c1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
return '{\'sunk\': %s, \'damaged\': %s, \'not_touched\': %s, \'points\': %s}' %(sunk, damaged, not_touched, points)
The couples in attacks contains (x, y) coordinates which must be list index.
I make the assumption that they are randomly generated, make sure that:
0 <= x < len(board[0])
0 <= y < len(board)
all( len(board[0]) == len(board[row]) for row in board)

Error in return in trace function

I am trying to perform dynamic programming for approximate pattern matching in this code.Once the matrix is created,I am trying to trace back to my answer using the function trace.But when I run the program,the trace function is not returning any result and the program isn't getting terminated.
class Structure :
def __init__(self):
self.vertical =[]
self.horizontal =[]
self.diagnol=[]
def merge(self, s):
for i in s.vertical :
self.vertical.append(i)
for i in s.horizontal :
self.horizontal.append(i)
for i in s.diagonal:
self.diagonal.append(i)
def __str__(self):
return "horizontal \n"+str(self.horizontal) +"\n vertical \n"+str(self.vertical)+"\n diagonal"+str(self.diagonal)
def posList(pattern, text): #determine the positions in the matrix
retList = list()
textList = [x for x in text.strip()]
for i, char1 in enumerate(pattern):
textPos = [j for j, char2 in enumerate(textList) if char1==char2]
for j in textPos:
retList.append((i+1,j+1))
return retList
def trace(M,text,pattern,k) :
positions=posList(pattern,text)
struct = Structure()
for i in range(0,2):
for j in range(0,7):
while M[i,j]<=k and M[2,j]!=0:
if M[i,j] == M[i,j-1]+1:
struct.horizontal.append(j)
j -= 1
elif M[i,j] == M[i-1,j]+1:
struct.vertical.append(i)
i -= 1
elif (i+1,j+1)in positions and M[i,j]==M[i-1,j-1] :
struct.diagonal.append((i,j))
i -= 1
j -= 1
elif (i+1,j+1) not in positions and M[i,j]==M[i-1,j-1]+1 and M[i,j]==M[i-1,j]+1:
struct.vertical.append(i)
i-=1
print "error"
elif (i+1,j+1) not in positions and M[i,j]==M[i-1,j-1]+1 and M[i,j]==M[i,j-1]+1:
struct.horizontal.append(j)
j-=1
elif M[i,j]==M[i-1,j]+1 and M[i,j]==M[i,j-1]+1:
struct.vertical.append(i)
elif M[i,j]==M[i-1,j]+1 and M[i,j]==M[i,j-1]+1 and M[i,j]==M[i-1,j-1]+1:
struct.vertical.append(i)
i-=1
else :
pass
return struct
text='ACAGCAG'
pattern='GC'
n = len(pattern)
m = len(text)
text1=list(text)
pattern1=list(pattern)
M = [[0 0 0 0 0 0 0 0],[1 1 1 1 0 1 1 0],[2 2 1 2 1 0 1 1]]
#perform traceback
s= trace(M,text,pattern,1)
print s
s = trace(M, w, seq, max, 0, n-1)
print str(s)
print seq
result=real_string(s)
print "".join(result)
Can anyone suggest me where I maybe going wrong in the function ?

Categories

Resources