Python tablecheck error - python

def tableCheck(elev, n, m):
tablePosCount = 0
rowPosCount = 0
for r in range(1, n):
for c in range(1, m):
if elev[r][c] > 0:
tablePosCount = tablePosCount + 1
rowPosCount = rowPosCount + 1
print 'Number of positive entries in row ', r , ' : ', rowPosCount
print 'Number of positive entries in table :', tablePosCount
return tablePosCount
elev = [[1,0,-1,-3,2], [0,0,1,-4,-1], [-2,2,8,1,1]]
tableCheck(elev, 3, 5)
I'm having some difficulty getting this code to run properly. If anyone can tell me why it might being giving me this output
Number of positive entries in row 1 : 1
Number of positive entries in row 2 : 2
Number of positive entries in row 2 : 3
Number of positive entries in row 2 : 4
Number of positive entries in row 2 : 5
Number of positive entries in table : 5

There are three things in your code that I suspect are errors, though since you don't describe the behavior you expect, it's possible that one or more of these is working as intended.
The first issue is that you print out the "row" number every time that you see a new value that is greater than 0. You probably want to unindent the print 'Number of positive entries in row ' line by two levels (to be even with the inner for loop).
The second issue is that you don't reset the count for each row, so the print statement I suggested you move will not give the right output after the first row. You probably want to move the rowPosCount = 0 line inside the outer loop.
The final issue is that you're skipping the first row and the first value of each later row. This is because your ranges go from 1 to n or m. Python indexing starts at 0, and ranges exclude their upper bound. You probably want for r in range(n) and for c in range(m), though iterating on the table values themselves (or an enumeration of them) would be more Pythonic.

Related

My Function To Count The Largest Binary Gap Doesn't Work But I Can't Figure Out Why

I'm working through the Codility problems and I have gotten the first one almost correct. The task is to write a function which returns the longest binary gap (a sequence of 0s in between 1s) in a binary number. I have gotten all of the test numbers correct apart from 9, which should be 2 (its binary representation is 1001) but which my function returns as 0. I can't seem to figure out why.
My function is as follows:
def Solution(N):
x = bin(N)[2:]
x_string = str(x)
y = (len(x_string))
count = 0
max = 0
for index, item in enumerate(x_string):
if item == "1":
count = 0
elif item == "0" and x_string[index + 1:y-1] != "0"*(y -1 - (index + 1)):
count = count + 1
if count > max:
max = count
print(max)
The complicated indexing and second condition in the elif statement is so that when a 0 is not contained between two 1s then it isn't recognised as the beginning of a binary gap e.g. when the for loop looks at the second character in bin(16) = 10000, it doesn't set count to 1 because all of the remaining characters in the string are also zero.
Simple solution
x_string[index + 1:y-1] != "0"
this bit wants to take a look at the whole string that's left, but the end argument isn't inclusive,it's exluded, so if string length = 4; string[0:4] is the whole string.
source: https://docs.python.org/3/tutorial/introduction.html
-Sam

How to print list of numbers but counting in like a pyramid fashion in IDLE

I'm trying to make a loop that prints numbers exactly like this:
1
12
123
1234
12345
I already have this pattern down for different characters, and can even print this:
1
22
333
4444
55555
But I'm having a big headache trying to figure out how I can make it count. Any help would be greatly appreciated.
Here is the code I have to print the list above:
for row in range (number_of_rows + 1):
for column in range(row)
print (row, end='')
print()
Sorry, I was just going to make a comment, but this will be easier:
for row in range (number_of_rows + 1):
for column in range(row)
print (column+1, end='') #<-- put column here instead of row and add a "+1"
print()
Some more details of what is going on:
for row in range (number_of_rows + 1):
Iterate from zero to number_of_rows. e.g. if number of rows was 5 this would iterate through a row of 0,1,2,3,4,5
for column in range(row):
For each row iterate from 0 to the row number minus 1. e.g. row 3 would iterate through 0, 1, 2
print (row+1, end='')
Print the column, one digit at a time. To start the row at 1 we need to add 1
If I'm understanding correctly, you could do something like
for i in range(1, rows + 1):
print(''.join(str(j) for j in range(1, i + 1)))
outputs:
1
12
123
1234
12345

subtract n values from input python

I haven't found anything even relevant to my question, so i may be asking it wrong.
I am working on an exercise where I am given sequential values starting at 1 and going to n, but not in order. I must find a missing value from the list.
My method is to add the full 1 => n value in a for loop but I can't figure out how to add n - 1 non-sequential values each as its own line of input in order to subtract it from the full value to get the missing one.
I have been searching modifications to for loops or just how to add n inputs of non-sequential numbers. If I am simply asking the wrong question, I am happy to do my own research if someone could point me in the right direction.
total = 0
for i in range (1 , (int(input())) + 1):
total += i
print(total)
for s in **?????(int(input()))**:
total -= s
print(total)
sample input:
5
3
2
5
1
expected output: 4
To fill in the approach you're using in your example code:
total = 0
n = int(input("How long is the sequence? "))
for i in range(1, n+1):
total += i
for i in range(1, n):
total -= int(input("Enter value {}: ".format(i)))
print("Missing value is: " + str(total))
That first for loop is unnecessary though. First of all, your loop is equivalent to the sum function:
total = sum(range(1,n+1))
But you can do away with any iteration altogether by using the formula:
total = int(n*(n+1)/2) # division causes float output so you have to convert back to an int
I don't know if you are supposed to create the initial data (with the missing item), so I added some lines to generate this sequence:
import random
n = 12 # or n = int(input('Enter n: ')) to get user input
# create a shuffled numeric sequence with one missing value
data = list(range(1,n+1))
data.remove(random.randrange(1,n+1))
random.shuffle(data)
print(data)
# create the corresponding reference sequence (without missing value)
data2 = list(range(1,n+1))
# find missing data with your algorithm
print("Missing value =", sum(data2)-sum(data))
Here is the output:
[12, 4, 11, 5, 2, 7, 1, 6, 8, 9, 10]
Missing value = 3

How to change values in nested list python

The matrix represents cell points. If we imagine these cell points being a grid, we need to make the values within the matrix equal to the input T1 in quadrants 2 and 4 and the values input T2 for quadrants 1 and 3. As in, from row 0 to 2 and column 0 to 3 it should be the value T1. Also, I need to make this appear as cells, with lines in between all rows/columns.
#input values needed
A = input("Enter a value for the first heater/cooler temp: ")
B = input("Enter a value for the second heater/cooler temp: ")
T1 = input("Enter a value for the first initial plate temp: ")
T2 = input("Enter a value for the second initial plate temp: ")
#the stabilizing criterion value
matrix = []
for row in range(0,6):
matrix.append([])
for column in range(0,9):
matrix[row].append(column)
for row in matrix:
print(row)
In this code, row in range(0,6) refers to all positions of the matrix that are in the first row, then second, and so on. It loops over all the rows.
So matrix[0][x] refers to all the positions in the 0th row (and you can access each position by setting x = 1, 2, ...).
What you want to do, is set values to T1 for a specific set of rows and columns, right?
Since you are anyway looping through all the rows and columns, you can check if at any point, the combination of row and column falls in the desired range:
if row < 3 and column < 4:
matrix[row][column] = T1
What this does is, whenever the combination of row and column numbers falls in the range that is, row = 0 to 2 and column = 0 to 3, it sets the value at those positions in the matrix, to T1.
Does this answer your question?
Now about the printing part, you can try a function like this:
def printy(P):
for i in range(len(P[0])):
print '---',
print
for i in range(len(P)):
for j in range(len(P[0])):
print P[i][j], '|',
print
for i in range(len(P[0])):
print '---',
print

Adding a triangle up from the bottom rows

I'm taking some guidance from this question (Max path triangle (Python)) but I stumbled upon it after I already started to write out what I thought.
I want to find the maximum of numbers within a triangle, leading from the bottom to the top. So once the loops reach the end the final position of the triangle will be the largest addition of the numbers from the rows below.
For instance...if this was the triangle:
2
3 7
8 2 10
2 6 9 4
It adds row n with row n-1 to mind the maximum values, so if my code ran the triangle would look like this after one iteration.
2
3 7
14 11 19
However the code I've written seems to not replace the elements in the list above.
for i in range(len(a)-1, 0, 1):
for j in range(0, len(a[i])-1, 1):
'''
i = Row position
j = Column position
'''
a[i-1][j] = max(a[i][j] + a[i-1][j], a[i][j+1] + a[i-1][j])
print a
I know it works, because when I put in numbers to check it spits out the correct answer. From the triangle I provided, the first numbers checked would be 2+8 and 6+8, making 14 the correct answer.
So what is wrong with my code?
Thanks :)
In your first for statement, you need to change the delta to -1. You can't go from len(a)-1 to 0 with positive numbers
for i in range(len(a)-1, 0, -1):
for j in range(0, len(a[i])-1, 1):
'''
i = Row position
j = Column position
'''
a[i-1][j] = max(a[i][j] + a[i-1][j], a[i][j+1] + a[i-1][j])
print a

Categories

Resources