time: na
def diagonalDifference(arr):
right_d = 0
left_d = 0
for i in range(len(arr)):
right_d += arr[i][i]
left_d += arr[len(arr)-1-i][i]
return(abs(right_d - left_d))
arr = [[1,2,3],[4,5,6],[7,8,11]]
print(diagonalDifference(arr))
def diagonalDifference_T1(arr):
left_d = sum( arr[len(arr)-1-i][i] for i in range(len(arr)) )
right_d = sum( arr[i][i] for i in range(len(arr)) )
return(abs(right_d - left_d))
print(diagonalDifference_T1(arr))
def diagonalDifference_T2(arr):
diff = sum( arr[i][i] - arr[len(arr)-1-i][i] for i in range(len(arr)) )
return abs(diff)
print(diagonalDifference_T2(arr))
time: < 5min
Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.
def plusMinus(arr):
pos = 0
neg = 0
zeros = 0
for a in arr:
if a == 0:
zeros += 1
elif a < 0:
neg += 1
elif a > 0:
pos += 1
else:
pass
print(pos/len(arr))
print(neg/len(arr))
print(zeros/len(arr))
def staircase(n):
for stair in range(n):
blanks = ' ' * (n - stair - 1)
staircase = '#' * (stair+1)
print(blanks + staircase)
# refactor 1
def staircase(n):
for m in range(n):
print((n - m - 1) * ' ' + (m + 1) * '#')
# refactor 2 with rjust
def staircase(n):
for i in range(n):
print(('#'*(i+1)).rjust(n))
staircase(6)