Python - scope variables returning none - python-3.x

I'm trying to build a grid based of a function i'm creating. I have assigned inner variables one for the
grid1(number):
D = ('-' * number)
S = (' ' * number)
H = print('+'+ D +'+' + D + '+')
V = print('|'+ S + '|' + S + '|' '\n')
print( H '\n' (V * number) + H '\n'+ (V * number) + H)
Basically im trying to create a grid that is 2 x 2, when it prints the V variable a second time, or even the next H, the variable returns as None. To my knowledge, I did not create an iterator, therefore the variable should still be assigned.
Am i missing something with scope variables ?

I assume you wanted to assign the strings to H and V, then use those again in the next print statement. In that case you need to remove the first two print statements and only do the assignment to the variables. With some other fixes, this results in:
def grid1(number):
D = ('-' * number)
S = (' ' * number)
H = '+'+ D +'+' + D + '+'
V = '|'+ S + '|' + S + '|' '\n'
print( H + '\n' + (V * number) + H + '\n' + (V * number) + H)
Which leads to for example:
>>> grid1(3)
+---+---+
| | |
| | |
| | |
+---+---+
| | |
| | |
| | |
+---+---+

Related

('%02x'):format(Number) in Node Js

Trying to convert lua encryption to Node.JS, just need this in it.
("%02x"):format(c)
Once, I got that I'll have it in node.js, so
I tried buffer and it didn't work.
Tried a few other things, and they also didn't work.
Orginal post for this encryption: Low impact encryption formula for ROBLOX Lua
Lua Code:
local Key53 = 8186484168865098
local Key14 = 4887
local inv256
function encode(str)
if not inv256 then
inv256 = {}
for M = 0, 127 do
local inv = -1
repeat
inv = inv + 2
until inv * (2*M + 1) % 256 == 1
inv256[M] = inv
end
end
local K, F = Key53, 16384 + Key14
return (str:gsub('.',
function(m)
local L = K % 274877906944 -- 2^38
local H = (K - L) / 274877906944
local M = H % 128
m = m:byte()
local c = (m * inv256[M] - (H - M) / 128) % 256
K = L * F + H + c + m
--print("lol ".. c)
--print(('%02x'):format(c))
return ('%02x'):format(c)
end
))
end
function decode(str)
local K, F = Key53, 16384 + Key14
return (str:gsub('%x%x',
function(c)
local L = K % 274877906944 -- 2^38
local H = (K - L) / 274877906944
local M = H % 128
c = tonumber(c, 16)
local m = (c + (H - M) / 128) * (2*M + 1) % 256
K = L * F + H + c + m
return string.char(m)
end
))
end
The %02x just convert a decimal to hex. In JS it could be done that way:
function toHex(value) {
let hex = value.toString(16);
if ((hex.length % 2) > 0) {
hex = "0" + hex;
}
return hex;
}
Outputs:
toHex(120) // 78
('%02x'):format(120) -- 78

When appending a tuple to a list, I can append (a + b + c) or (a, b + c) or (a + b, c) but appending (a, b ,c) causes the program to refuse to run

Here's the code
def check_right_angle(a, b, c):
if a**2 + b**2 == c**2:
return True
return False
def mn_to_abc(m, n):
return m**2 - n**2, 2 * m * n, m**2 + n**2
list_solutions = []
for i in range(1001): #Getting all primitive triples using Euclid's formula <= 1000
list_solutions.append([])
if i == 0:
continue
for m in range(1, int(i/2) - 1):
n = int(i / (2 * m) - m)
if m > n and n > 0:
a, b, c = mn_to_abc(m, n)
if check_right_angle(a, b, c) and a + b + c == i:
list_solutions[i].append((a, b, c))
for item in list_solutions: #Getting the remaining triples by using the primitive triples
for abc in item:
for i in range(1, 85): # 85 since 3x + 4x + 5x = 1000 => x = 83.3333 = 84
try:
new_a = abc[0] * i
new_b = abc[1] * i
new_c = abc[2] * i
if new_a + new_b + new_c <= 1000:
list_solutions[new_a + new_b + new_c].append((new_a, new_b, new_c))
else:
break
except:
continue
print(len(list_solutions[120]))
print(list_solutions[120])
The situation is mostly explained in the title but this code refuses to run unless line 30 is replaced with either one of the following lines:
list_solutions[new_a + new_b + new_c].append((new_a+ new_b, new_c))
list_solutions[new_a + new_b + new_c].append((new_a+ new_b+ new_c))
list_solutions[new_a + new_b + new_c].append((new_a, new_b+ new_c))
I've even tried to append it as a list instead of a tuple but to no avail. Such a weird thing to run into.
Never mind fellas, just had an epiphany. Turns out adding to a list you're iterating is a terrible, terrible idea. Before line 30 I added this code:
if not (new_a, new_b, new_c) in list_solutions[new_a + new_b + new_c]:
You might have noticed that I'm still adding to that same list I'm iterating through, but for some reason, as long as the items in that list don't repeat themselves, everything is fine.
I would close this question now, but it's telling me I can only accept my own answer in 2 days.

VBA results in #VALUE! only when For loop is used

I am writing a function with a For loop, and ultimately the value of the function will depend on the output of the For loop. For now as a test, the value of the function is a constant. If the For loop is in the code, the function results in #Value!. If I remove the For loop, the output is the specified constant value. How does the For loop need to be specified to avoid this? Good values for Tc and Th as a test would be 100 and 300, respectively.
Function kndT(material As Integer, Tc As Double, Th As Double) As Variant
Dim x As Double
Select Case material
Case 4
If Th > 300 Then
Tmax = 300
Else
Tmax = Th
End If
A = 0.07918
b = 1.0957
c = -0.07277
D = 0.08084
e = 0.02803
f = -0.09464
g = 0.04179
h = -0.00571
i = 0
End Select
hh = (Tmax - Tc) / 999
fi = 0
nc = 1
For i = 1 To 999
Temp = (Tc + i * hh)
x = Log(Temp) / Log(10#)
y = A + b * x + c * x ^ 2 + D * x ^ 3 + e * x ^ 4 + f * x ^ 5 + g * x ^ 6 + h * x ^ 7 + i * x ^ 8
fn = 10 ^ y
If nc = 3 Then
fi = fi + 2 * fn
nc = 1
Else
fi = fi + 3 * fn
nc = nc + 1
End If
Next i
kndT = 2
End Function

Maze solver won't backtrack in Python

There are a couple of maze questions similar to this one but none of them ever really go into the why it won't work.
I don't need precise answers. I just need to know why this particular thing doesn't work.
This is the bit of my class Maze that I need help with.
ysize in my example is 10
xsize is 10
xend is 20 (changing it to 19 messes with the results and doesn't draw anything)
yend is 10 (changing it to 9 does this too)
class Maze:
def __init__(self):
self.maze = []
self.xstart = None
self.ystart = None
self.xend = None
self.yend = None
self.xsize = None
self.ysize = None
def read_maze(self, filename):
maze_list = []
f_maze = open(filename)
size = f_maze.readline().split() #
start = f_maze.readline().split() #
end = f_maze.readline().split() #
self.xstart = int(start[1])
self.ystart = int(start[0])
self.xend = (int(end[1])*2)
self.yend = (int(end[0])*2)
self.xsize = (int(size[1])*2)
self.ysize = (int(size[0])*2)
lines = f_maze.readlines()
for line in lines:
maze_list.append(list(line[:len(line)]))
self.maze = maze_list # Assigns to class
def __str__(self):
return ("".join(''.join(line) for line in self.maze))
def solve(self, x, y):
if y > (self.ysize) or x > (self.xsize):
print("1")
return False
if self.maze[y][x] == self.maze[self.yend][self.xend]:
print("2")
return True
if self.maze[y][x] != " ":
print("3")
return False
self.maze[y][x] = "o" # MARKING WITH o for path already taken.
if self.solve(x+1,y) == True:
return True
elif self.solve(x,y+1) == True:
return True
elif self.solve(x-1,y) == True:
return True
elif self.solve(x,y-1) == True:
return True
self.maze[y][x] = " " # ELSE I want it to be replaced with space
return False
This is the current result.
---------------------
|ooooooooooooo| | |
|-+-+-+ +-+-+o+ + +-|
| | | |o| |
| +-+-+ + +-+-+-+ + |
| | | | | |
|-+-+ + + + +-+ +-+-|
| | |
|-+ +-+-+-+-+-+ +-+ |
| | | |
---------------------
I want it like this:
---------------------
|ooooooo | | |
|-+-+-+o+-+-+ + + +-|
| | o| | | |
| +-+-+o+ +-+-+-+ + |
| o| | | | |
|-+-+ +o+ + +-+ +-+-|
| |ooooooooooooo|
|-+ +-+-+-+-+-+ +-+o|
| | | o|
---------------------
I don't know how to fix the indentation format here I apologize. That is my whole code. These are my test statements:
maze = Maze()
maze.read_maze(filename)
maze.solve(maze.xstart, maze.ystart)
print(maze)
The files go in this format saved as .txt files.
5 10
1 1
5 10
---------------------
| | | |
|-+-+-+ +-+-+ + + +-|
| | | | | |
| +-+-+ + +-+-+-+ + |
| | | | | |
|-+-+ + + + +-+ +-+-|
| | |
|-+ +-+-+-+-+-+ +-+ |
| | | |
---------------------
The problem is that as your file stands, xend, yend is (10, 20). To debug why it's not working, you can print(self.maze[self.yend][self.xend]) which returns a dash "-". Now, when your recursive call's (x, y) pair reaches its first dash, it tests True for the line
if self.maze[y][x] == self.maze[self.yend][self.xend]:
and thinks it has solved the maze. Rather, we want to test
if (y, x) == (self.yend, self.xend):
That is, test the coordinates, not the value of the square.
Another point: examining the actual location of the goal, we see that it's here:
+-+ +-+ |
| |
--------- <= this corner is the goal!
Which is unreachable if moving in strictly cardinal directions. Moving the goal a square up or to the left would put it within bounds of the solver algorithm.
This was sufficient to get the code working for me and hopefully is enough to get you moving again.

MDX NON EMPTY multidimension axis

I'm writting MDX code in VBA and I have to put the data in Excel.
SELECT
{ [Measures].[VL PROD], [Measures].[Impostos], [Measures].[RecLiqProd], [Measures.[ValorMgProd], [Measures].[QTD ITENS] ,[Measures].[VL FRETE] } ON 0,
NON EMPTY ( { Descendants( [Produto].[Produto].[Departamento], 5 ) } ) ON 1,
NON EMPTY ( { [Data Pedido].[Data].[Ano].&[2014].&[2].&[6].&[1]:[Data Pedido].[Data].[Ano].&[2014].&[2].&[6].&[26] } ON 2,
NON EMPTY ( { [Unidade Negócio].[Unidade Negócio].&[Unidade 1], [Unidade Negócio].[Unidade Negócio].&[Unidade 2], [Unidade Negócio].[Unidade Negócio].&[Unidade 3] } ) ON 3
FROM [Rentabilidade]
WHERE ( - Extract( { [Livre de Debito] }, [Meio Pagamento].[Meio Pagamento]) )
For i = 0 To cst.Axes(1).Positions.Count - 1
For j = 0 To cst.Axes(2).Positions.Count - 1
For k = 0 To cst.Axes(3).Positions.Count - 1
'If cst(0, i, j, k) * cst(1, i, j, k) * cst(2, i, j, k) * cst(3, i, j, k) * cst(4, i, j, k) * cst(5, i, j, k) <> "" Then
Cells(a, 1) = cst.Axes(1).Positions(i).Members(0).Caption
Cells(a, 2) = cst.Axes(2).Positions(j).Members(0).Caption
Cells(a, 3) = cst.Axes(3).Positions(k).Members(0).Caption
Cells(a, 4) = cst(0, i, j, k)
Cells(a, 5) = cst(1, i, j, k)
Cells(a, 6) = cst(2, i, j, k)
Cells(a, 7) = cst(3, i, j, k)
Cells(a, 8) = cst(4, i, j, k)
Cells(a, 9) = cst(5, i, j, k)
a = a + 1
'End If
Next k
Next j
Next i
The problem is that I get plenty of empty rows; I'd like to know how I can remove them.
For example, I'm getting the following:
Id | Data | Bandeira | impostos | recliq | ValorMrg | Qtd Item | Vl Frete
10 | 40230 | Unidade 1 | | | | |
10 | 40230 | Unidade 2 | | | | |
10 | 40230 | Unidade 3 | 0,2 | 2032 | 100 | 1000 | 323
32 | 40231 | Unidade 3 | | | | |
32 | 40232 | Unidade 3 | | | | |
32 | 40233 | Unidade 3 | 0,2 | 32 | 321 | 5045 | 323
I thought I had understood the difference between non empty and nonempty (from http://beyondrelational.com/modules/2/blogs/65/posts/11569/mdx-non-empty-vs-nonempty.aspx) but maybe I'm missing something.
Can anyone help me?
If you want to have a two dimensional report, why do you run a four dimensional query?
I would think that the following MDX
SELECT
{ [Measures].[VL PROD], [Measures].[Impostos], [Measures].[RecLiqProd], [Measures.[ValorMgProd], [Measures].[QTD ITENS] ,[Measures].[VL FRETE] }
ON 0,
NON EMPTY
{ Descendants( [Produto].[Produto].[Departamento], 5 ) } )
*
{ [Data Pedido].[Data].[Ano].&[2014].&[2].&[6].&[1]:[Data Pedido].[Data].[Ano].&[2014].&[2].&[6].&[26] }
*
{ [Unidade Negócio].[Unidade Negócio].&[Unidade 1], [Unidade Negócio].[Unidade Negócio].&[Unidade 2], [Unidade Negócio].[Unidade Negócio].&[Unidade 3] } )
ON 1
FROM [Rentabilidade]
WHERE ( - Extract( { [Livre de Debito] }, [Meio Pagamento].[Meio Pagamento]) )
would deliver what you want. In this case, the NON EMPTY on Axis 1 would be evaluated for each tuple of the cross product of the three hierarchies against the columns axis.
Of course, then you would have to change your VBA code accordingly, as you now have only one axis for the rows, but it has three positions instead of one.

Resources