Reputation: 5052
I m trying to create the below pattern using the below code
7
4 8
2 5 9
1 3 6 10
def createpattern(n=4,max_val=10):
pattern = []
for x in range(1,n+1):
temp = []
step = 2
val = x
bool_flag = 1
while bool_flag == 1:
temp += [val]
if val == max_val:
print('----->')
bool_flag = 0
print('before break')
break
else:
val = val + step
step += 1
print('after break')
print(temp)
max_val = max_val - 1
pattern.append(temp)
The break under while loop is working as expected
I m able to generate the first row however , the range in for loop is not moving to the next iteration value it is stuck at 1.
I have tried adding a continue at the end after append , however the loop is still stuck.
I m unable to figure out a way to rectify the above nested loop , ideally it should move to the next iteration value which I m unable to figure out why
Any leads would be helpful
Upvotes: 2
Views: 162
Reputation: 5052
I was able to resolve it, the approach that I was taking was very naive and had to research a bit on the patterns
Useful link for any pattern sequence formulae can be found here - here
Over the course the numbers in the required pattern tends to follow a trend and are a direct derivative of Triangular Numbers
Code Snippet --
def createpattern(x, y):
pattern = []
traingular_nums = [n*(n+1)/2 for n in range(1,y+x+1)]
pattern.append(traingular_nums)
for i in range(2,x+y+1):
k = (i*(i-1)/2) + 1 <----- Formulae for Triangular Numbers
temp = []
temp.append(k)
for z in range(1,len(pattern[i-2])-1):
v = temp[z-1] + pattern[i-2][z+1] - pattern[i-2][z]
temp.append(v)
pattern.append(temp)
return pattern
The pattern was part of Google Foobar Challenge
Upvotes: 0
Reputation: 36
The loop gets stuck due to the if val == max_val
condition and incorrect step calculations. When the second row is created, the initial value of step
should be 3, not 2. The result currently produced is [2, 4, 7, 11, ...]
and the loop never terminates, since there is never a 9 in the array. That applies to the rest of the rows as well.
Upvotes: 0
Reputation: 659
When calling the function with the default arguments and looking at it in a debugger, on the second iteration it produces [2, 4, 7, 11, 16 ...
and goes on forever. Because none of these values is equal to max_val, val == max_val
is never true. After changing it to if val >= max_val:
, I get the following output:
----->
before break
after break
[1, 3, 6, 10]
----->
before break
after break
[2, 4, 7, 11]
----->
before break
after break
[3, 5, 8]
----->
before break
after break
[4, 6, 9]
Upvotes: 1