Related
In this code I need to exit loop on certain condition. if position + 1 == len(triangle)
Maybe I am not good at Python and don't understand clearly its behaviour.
It is not listening to my command and keep calling same function instead of leaving the loop.
The only other thing I tried is to call break in the loop itself when same condition is met but it is not working as well.
def max_value(list, index):
for _ in range(len(list)):
dictionary = dict()
maximum = max(list[index], list[index + 1])
dictionary['max'] = maximum
if maximum == list[index]:
dictionary['next_index'] = index
else:
dictionary['next_index'] = index + 1
return dictionary
total = 0
index = 0
skip = False
position = 0
def sliding_triangle(triangle):
global total
global index
global skip
global position
if not skip:
skip = True
total += triangle[0][0]
total += max_value(triangle[1], index).get("max")
index = max_value(triangle[1], index).get("next_index")
position = 2
sliding_triangle(triangle)
if position + 1 == len(triangle): return <-----------------HERE I AM EXPECTING IT TO EXIT
for row in range(position, len(triangle)):
values = max_value(triangle[row], index)
total += values.get("max")
index = values.get("next_index")
print(position, int(len(triangle)), index, values.get("max"), total)
position += 1
sliding_triangle(triangle)
return total
print(sliding_triangle([
[75],
[95, 64],
[17, 47, 82],
[18, 35, 87, 10],
[20, 4, 82, 47, 65],
[19, 1, 23, 75, 3, 34],
[88, 2, 77, 73, 7, 63, 67],
[99, 65, 4, 28, 6, 16, 70, 92],
[41, 41, 26, 56, 83, 40, 80, 70, 33],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
[63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
[ 4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],
]))
Hehey, Got it working finally, so the solution was to break from loop earlier.
I had to put the condition in the beginning of the loop otherwise it was doing the same process and condition was wrong.
total = 0
index = 0
skip = False
position = 0
def max_value(list, index):
for _ in range(len(list)):
dictionary = dict()
maximum = max(list[index], list[index + 1])
dictionary['max'] = maximum
if maximum == list[index]:
dictionary['next_index'] = index
else:
dictionary['next_index'] = index + 1
return dictionary
def sliding_triangle(triangle):
global total
global index
global skip
global position
if not skip:
skip = True
total += triangle[0][0]
total += max_value(triangle[1], index).get("max")
index = max_value(triangle[1], index).get("next_index")
position = 2
sliding_triangle(triangle)
for row in range(position, len(triangle)):
if position == int(len(triangle)): break <<<--------------- I HAD TO CALL BREAK EARLIER, OTHERWISE FOR LOOP WAS KEEP WORKING INSTEAD OF STOPPING
values = max_value(triangle[row], index)
total += values.get("max")
index = values.get("next_index")
position += 1
sliding_triangle(triangle)
return total
print(sliding_triangle([
[75],
[95, 64],
[17, 47, 82],
[18, 35, 87, 10],
[20, 4, 82, 47, 65],
[19, 1, 23, 75, 3, 34],
[88, 2, 77, 73, 7, 63, 67],
[99, 65, 4, 28, 6, 16, 70, 92],
[41, 41, 26, 56, 83, 40, 80, 70, 33],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
[63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
[ 4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],
]))
Recursive brute force solution
def sliding_triangle(triangle, row = 0, index = 0):
if row >= len(triangle) or index >= len(triangle[row]):
return 0 # row or index out of bounds
# Add parent value to max of child triangles
return triangle[row][index] + max(sliding_triangle(triangle, row+1, index), sliding_triangle(triangle, row+1, index+1))
Tests
print(sliding_triangle([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]))
# Output: 23
print(sliding_triangle([
[75],
[95, 64],
[17, 47, 82],
[18, 35, 87, 10],
[20, 4, 82, 47, 65],
[19, 1, 23, 75, 3, 34],
[88, 2, 77, 73, 7, 63, 67],
[99, 65, 4, 28, 6, 16, 70, 92],
[41, 41, 26, 56, 83, 40, 80, 70, 33],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
[63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
[ 4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],
]))
# Output: 1074
However, brute force approach times out on larges dataset
Optimized Solution
Apply memoization to brute force solution.
Uses cache to avoid repeatedly solving for subpaths of a parent triangle node
Code
def sliding_triangle(triangle):
' Wrapper setup function '
def sliding_triangle_(row, index):
' Memoized function which does the calcs'
if row >= len(triangle) or index >= len(triangle[row]):
return 0
if not (row, index) in cache:
# Update cache
cache[(row, index)] = (triangle[row][index] +
max(sliding_triangle_(row+1, index),
sliding_triangle_(row+1, index+1)))
return cache[(row, index)]
cache = {} # init cache
return sliding_triangle_(0, 0) # calcuate starting from top most node
Tests
Same results as brute force solution for simple test cases
Works on large dataset i.e. https://projecteuler.net/project/resources/p067_triangle.txt
Find and Show Optimal Path*
Modify Brute Force to Return Path
Show highlighted path in triangle
Code
####### Main function
def sliding_triangle_path(triangle, row = 0, index = 0, path = None):
'''
Finds highest scoring path (using brute force)
'''
if path is None:
path = [(0, 0)] # Init path with top most triangle node
if row >= len(triangle) or index >= len(triangle[row]):
path.pop() # drop last item since place out of bounds
return path
# Select best path of child nodes
path_ = max(sliding_triangle_path(triangle, row+1, index, path + [(row+1, index)]),
sliding_triangle_path(triangle, row+1, index+1, path + [(row+1, index+1)]),
key = lambda p: score(triangle, p))
return path_
####### Utils
def getter(x, args):
'''
Gets element of multidimensional array using tuple as index
Source (Modified): https://stackoverflow.com/questions/40258083/recursive-itemgetter-for-python
'''
try:
for k in args:
x = x[k]
return x
except IndexError:
return 0
def score(tri, path):
' Score for a path through triangle tri '
return sum(getter(tri, t) for t in path)
def colored(r, g, b, text):
'''
Use rgb code to color text'
Source: https://www.codegrepper.com/code-examples/python/how+to+print+highlighted+text+in+python
'''
return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)
def highlight_path(triangle, path):
' Created string that highlight path in red through triangle'
result = "" # output string
for p in path: # Looop over path tuples
row, index = p
values = triangle[row] # corresponding values in row 'row' of triangle
# Color in red path value at index, other values are in black (color using rgb)
row_str = ' '.join([colored(255, 0, 0, str(v)) if i == index else colored(0, 0, 0, str(v)) for i, v in enumerate(values)])
result += row_str + '\n'
return result
Test
# Test
triangle = ([
[75],
[95, 64],
[17, 47, 82],
[18, 35, 87, 10],
[20, 4, 82, 47, 65],
[19, 1, 23, 75, 3, 34],
[88, 2, 77, 73, 7, 63, 67],
[99, 65, 4, 28, 6, 16, 70, 92],
[41, 41, 26, 56, 83, 40, 80, 70, 33],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
[63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
[ 4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],
])
path = sliding_triangle_path(triangle)
print(f'Score: {score(tri, path)}')
print(f"Path\n {'->'.join(map(str,path))}")
print(f'Highlighted path\n {highlight_path(tri, path)}')
Output
Score: 1074
Path
(0, 0)->(1, 1)->(2, 2)->(3, 2)->(4, 2)->(5, 3)->(6, 3)->(7, 3)->(8, 4)->(9, 5)->(10, 6)->(11, 7)->(12, 8)->(13, 8)->(14, 9)
Got my own correct answer for the kata, which can handle big triangles and passed all tests
def longest_slide_down(triangle):
temp_arr = []
first = triangle[-2]
second = triangle[-1]
if len(triangle) > 2:
for i in range(len(first)):
for _ in range(len(second)):
summary = first[i] + max(second[i], second[i + 1])
temp_arr.append(summary)
break
del triangle[-2:]
triangle.append(temp_arr)
return longest_slide_down(triangle)
summary = triangle[0][0] + max(triangle[1][0], triangle[1][1])
return summary
You can try using an else and a pass, like so:
def max_value():
# code
def sliding_triangle():
if not skip:
# code
if position + 1 == len(triangle):
pass
else:
for row in range(position, len(triangle)):
# code
return total
print sliding_triangle()
As far as I know, you can't interrupt a def by throwing a return in two or more different points of the script just like in Java. Instead, you can just place a condition that, whether is respected, you skip to the return. Instead, you continue with the execution.
I synthesized your code to let you understand the logic easier, but it's not a problem if I have to write it fully
I have a class like this
class A:
def __init__(self):
self.top_left = (1,2)
self.arr = np.reshape(np.arange(100), (10,10))
def __setitem__(self, key, val):
return self.arr[shifted(key, self.top_left)] = val
I want all the row indices appear in key to be shifted by 1 and all the column indices appear in key shifted by 2. Is it possible?
Edit:
Consider a = A() and a.arr to be
[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]]
Now when I set a[0,0] = 5, a.arr changes at index (1,2). Because it gets shifted by (1,2).
Again if I set a[3:6, 3:6] = np.ones((3,3)) then a.arr looks like this:
[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 1, 1, 1, 48, 49],
[50, 51, 52, 53, 54, 1, 1, 1, 58, 59],
[60, 61, 62, 63, 64, 1, 1, 1, 68, 69],
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]]
because all the index in the key, gets shifted by (1,2).
Edit 2:
Currently I am storing the values in a separate array. And then putting this whole array, back to arr.
self.arr2[key] = value
self.arr[self.top_left[1] : self.top_left[1] + self.shape[1],
self.top_left[0] : self.top_left[0] + self.shape[1],
] = self.arr2
self.shape is shape of the editable window in a.arr
Numpy array operate on builtin python slice or tuple.
shifter function decides what kind of index you passed.
import numpy as np
class A:
def __init__(self):
self.top_left = (1,2)
self.arr = np.reshape(np.arange(100), (10,10))
def __setitem__(self, key, val):
self.arr[self.shifter(key)] = val
def shifter(self, key):
if isinstance(key[0], slice):
shift_func = self.shifted_slice
else:
shift_func = self.shifted_point
return shift_func(key)
def shifted_slice(self, key):
row_slice, col_slice = key
row_offset, col_offset = self.top_left
return slice(row_slice.start + row_offset, row_slice.stop + row_offset), \
slice(col_slice.start + col_offset, col_slice.stop + col_offset)
def shifted_point(self, key):
row_num, col_num = key
row_offset, col_offset = self.top_left
return row_num + row_offset, \
col_num + col_offset
a = A()
a[0, 0] = 5
a[3:6, 3:6] = np.ones((3,3))
print(a.arr)
Outputs:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 5, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 1, 1, 1, 48, 49],
[50, 51, 52, 53, 54, 1, 1, 1, 58, 59],
[60, 61, 62, 63, 64, 1, 1, 1, 68, 69],
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
I am looking for a way to reshape the following 1d-numpy array:
# dimensions
n = 2 # int : 1 ... N
h = 2 # int : 1 ... N
m = n*(2*h+1)
input_data = np.arange(0,(n*(2*h+1))**2)
The expected output should be reshaped into (2*h+1)**2 blocks of shape (n,n) such as:
input_data.reshape(((2*h+1)**2,n,n))
>>> array([[[ 0 1]
[ 2 3]]
[[ 4 5]
[ 6 7]]
...
[[92 93]
[94 95]]
[[96 97]
[98 99]]]
These blocks finally need to be reshaped into a (m,m) matrix so that they are stacked in rows of 2*h+1 blocks:
>>> array([[ 0, 1, 4, 5, 8, 9, 12, 13, 16, 17],
[ 2, 3, 6, 7, 10, 11, 14, 15, 18, 19],
...
[80, 81, 84, 85, 88, 89, 92, 93, 96, 97],
[82, 83, 86, 87, 90, 91, 94, 95, 98, 99]])
My problem is that I can't seem to find proper axis permutations after the first reshape into (n,n) blocks. I have looked at several answers such as this one but in vain.
As the real dimensions n and h are quite bigger and this operation takes place in an iterative process, I am looking for an efficient reshaping operation.
I don't think you can do this with reshape and transpose alone (although I'd love to be proven wrong). Using np.block works, but it's a bit messy:
np.block([list(i) for i in input_data.reshape( (2*h+1), (2*h+1), n, n )])
array([[ 0, 1, 4, 5, 8, 9, 12, 13, 16, 17],
[ 2, 3, 6, 7, 10, 11, 14, 15, 18, 19],
[20, 21, 24, 25, 28, 29, 32, 33, 36, 37],
[22, 23, 26, 27, 30, 31, 34, 35, 38, 39],
[40, 41, 44, 45, 48, 49, 52, 53, 56, 57],
[42, 43, 46, 47, 50, 51, 54, 55, 58, 59],
[60, 61, 64, 65, 68, 69, 72, 73, 76, 77],
[62, 63, 66, 67, 70, 71, 74, 75, 78, 79],
[80, 81, 84, 85, 88, 89, 92, 93, 96, 97],
[82, 83, 86, 87, 90, 91, 94, 95, 98, 99]])
EDIT: Never mind, you can do without np.block:
input_data.reshape( (2*h+1), (2*h+1), n, n).transpose(0, 2, 1, 3).reshape(10, 10)
array([[ 0, 1, 4, 5, 8, 9, 12, 13, 16, 17],
[ 2, 3, 6, 7, 10, 11, 14, 15, 18, 19],
[20, 21, 24, 25, 28, 29, 32, 33, 36, 37],
[22, 23, 26, 27, 30, 31, 34, 35, 38, 39],
[40, 41, 44, 45, 48, 49, 52, 53, 56, 57],
[42, 43, 46, 47, 50, 51, 54, 55, 58, 59],
[60, 61, 64, 65, 68, 69, 72, 73, 76, 77],
[62, 63, 66, 67, 70, 71, 74, 75, 78, 79],
[80, 81, 84, 85, 88, 89, 92, 93, 96, 97],
[82, 83, 86, 87, 90, 91, 94, 95, 98, 99]])
Hey!
This relates to problem 18 from Euler's project (https://projecteuler.net/problem=18)
This code solved it, but I got an error (4th line):
Undefined variable: 'ans'Python(undefined-variable)
So, I want to understand why this happened
Also, let me know, if there are any flaws in my code
Thanks in advance
def brute(i, j, sum):
global ans
if i > len(l) - 1:
if sum > ans:
ans = sum
return None
brute(i + 1, j, sum + l[i][j])
brute(i + 1, j + 1, sum + l[i][j])
l = [
[75],
[95, 64],
[17, 47, 82],
[18, 35, 87, 10],
[20, 4, 82, 47, 65],
[19, 1, 23, 75, 3, 34],
[88, 2, 77, 73, 7, 63, 67],
[99, 65, 4, 28, 6, 16, 70, 92],
[41, 41, 26, 56, 83, 40, 80, 70, 33],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
[63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
[4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],
]
ans = 0
brute(0, 0, 0)
print(ans)
IMHO this is not a good use-case for globals, would be better to refactor the code like so:
def brute(i, j):
if i > len(l) - 1:
return 0
return l[i][j]+max(brute(i + 1, j), brute(i + 1, j + 1))
I've flipped the logic around to accomplish though, the code works by picking the maximum sum from its subtree
You ideally want to save usage of global variables for system-wide settings and such
I want to create multiple list by using a single loop with some condition.
I know how to create one list which is done by appending, but here all the results of loop goes in one single list which is not what I want.
So lets say we run a loop on first 100 numbers and I want to create multiple list where first list contains numbers till 5 , second from 6 to 10, third from 11 to 15 and so.
This code is just for one list created by me.
number = range(100)
first = []
for i in number:
first.append(i)
first
Something like that:
l = []
for x in range(6, 102, 5):
l.append([y for y in range(x-5, x)])
Output:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35],
[36, 37, 38, 39, 40],
[41, 42, 43, 44, 45],
[46, 47, 48, 49, 50],
[51, 52, 53, 54, 55],
[56, 57, 58, 59, 60],
[61, 62, 63, 64, 65],
[66, 67, 68, 69, 70],
[71, 72, 73, 74, 75],
[76, 77, 78, 79, 80],
[81, 82, 83, 84, 85],
[86, 87, 88, 89, 90],
[91, 92, 93, 94, 95],
[96, 97, 98, 99, 100]]
The range function takes three parameters start, stop and step.
Try this, This will create what you want:
lists = []
for i in range(1, 100, 5): # range(start, end, size_of_each_list)
lists.append(list(range(i,i + 5)))
The lists will be:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35],
[36, 37, 38, 39, 40],
[41, 42, 43, 44, 45],
[46, 47, 48, 49, 50],
[51, 52, 53, 54, 55],
[56, 57, 58, 59, 60],
[61, 62, 63, 64, 65],
[66, 67, 68, 69, 70],
[71, 72, 73, 74, 75],
[76, 77, 78, 79, 80],
[81, 82, 83, 84, 85],
[86, 87, 88, 89, 90],
[91, 92, 93, 94, 95],
[96, 97, 98, 99, 100]]
This is one way to do it. Basically you create an iterator from your list and then get all the lists you want from it.
number = range(100)
number_iter = iter(number)
lists = []
while True:
try:
lists.append([next(number_iter) for _ in range(5)])
except StopIteration as e:
break
lists
this has the advantage that your initial `number' list can be anything...
I would use second list inside the first.
number = range(100)
cnt = 0
first = []
second = []
for i in number:
cnt += 1
second.append(i)
if cnt == 5:
first.append(second)
cnt = 0
second = []
first
output:
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
...
[95, 96, 97, 98, 99]]
I would do a list comprehension similar to this:
[[i, i+1, i+2, i+3, i+4] for i in range (1, 100, 5)]
The output would look like this:
[[1, 2, 3, 4, 5],
...,
[96, 97, 98, 99, 100]]
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
It is possible. We can do this by directly creating variables in our globals() environment.
(Use locals() if it should exist only in the enclosing function).
You can do this with the following code:
# Run the loop
for i in range(100):
# for 0-4, list_name = 'list_1'
list_name = 'list_' + str(i//5 + 1)
# Try to append to that list
try:
globals()[list_name].append(i)
# If if doesn't exist, create it on the run!
except KeyError:
globals()[list_name] = [i]
This globals()[list_name] = [i] first:
Gets the module environment dictionary.
Creates list_name variable.
Initialises it to a list containing i.
Let us print them all:
for i in range(20):
# Print list_1 through list_20
list_name = 'list_' + str(i+1)
print(list_name + ':', globals()[list_name])
You get:
list_1: [0, 1, 2, 3, 4]
list_2: [5, 6, 7, 8, 9]
list_3: [10, 11, 12, 13, 14]
list_4: [15, 16, 17, 18, 19]
list_5: [20, 21, 22, 23, 24]
list_6: [25, 26, 27, 28, 29]
list_7: [30, 31, 32, 33, 34]
list_8: [35, 36, 37, 38, 39]
list_9: [40, 41, 42, 43, 44]
list_10: [45, 46, 47, 48, 49]
list_11: [50, 51, 52, 53, 54]
list_12: [55, 56, 57, 58, 59]
list_13: [60, 61, 62, 63, 64]
list_14: [65, 66, 67, 68, 69]
list_15: [70, 71, 72, 73, 74]
list_16: [75, 76, 77, 78, 79]
list_17: [80, 81, 82, 83, 84]
list_18: [85, 86, 87, 88, 89]
list_19: [90, 91, 92, 93, 94]
list_20: [95, 96, 97, 98, 99]
Note: Why not have some number fun! See python inflect package.