How to obtain partial derivative symbol in mathematica - wolfram-mathematica

I would like Mathematica to return symbolic partial derivative instead of actual derivative.
StressMatrix = ( {
{\[Sigma]11, \[Sigma]12, \[Sigma]13},
{\[Sigma]21, \[Sigma]22, \[Sigma]23},
{\[Sigma]31, \[Sigma]32, \[Sigma]33}
} );
varList = ( {
{\[Rho], \[Theta], z}
} )
StressMatrix[[2, 3]]
varList[[1, 1]]
D[StressMatrix[[2, 3]], varList[[1, 1]]]
The code above returns zero but I would like it to return symbolically Partial derivative of Sigma[[2,3]] with respect to rho.
How can I do this?

You can use Inactivate,
Inactivate[D[StressMatrix[[2, 3]], varList[[1, 1]]]]
or Hold
Hold[D[StressMatrix[[2, 3]], varList[[1, 1]]]]

Various methods, including specified values (which need to be set after hold).
Clear[σ23]
StressMatrix = Map[Hold,
{{σ11, σ12, σ13}, {σ21, σ22, σ23}, {σ31, σ32, σ33}}, {2}];
varList = {{ρ, θ, z}};
σ23 = 4 ρ^2;
expr = StandardForm[
"∂" <> StringTake[ToString[StressMatrix[[2, 3]]], {6, -2}]/
"∂" <> ToString[varList[[1, 1]]]];
symbolic = Inactive[D][ReleaseHold#StressMatrix[[2, 3]], varList[[1, 1]]];
result = D[ReleaseHold#StressMatrix[[2, 3]], varList[[1, 1]]];
Row[{expr, " = ", symbolic, " = ", result}]
Alternatively
symbolic2 = StringJoin["D[",
StringTake[ToString[StressMatrix[[2, 3]]], {6, -2}], ",",
ToString#varList[[1, 1]], "]"];
Row[{expr, " = ", symbolic2, " = ", ToExpression[symbolic2]}]
And finally
Clear[σ23]
StressMatrix =
Map[HoldForm, {{σ11, σ12, σ13}, {σ21, σ22, σ23}, {σ31, σ32, σ33}}, {2}];
varList = {{ρ, θ, z}};
σ23 = 4 ρ^2;
expr = StandardForm[
"∂" <> ToString[StressMatrix[[2, 3]]]/
"∂" <> ToString[varList[[1, 1]]]];
symbolic = Inactive[D][ToString#StressMatrix[[2, 3]], varList[[1, 1]]];
result = D[ReleaseHold#StressMatrix[[2, 3]], varList[[1, 1]]];
Row[{expr, " = ", symbolic, " = ", result}]

Related

Prepare the Bunnies Escape - Foobar

I've been at this for a while and for the life of me I cannot figure out why I cannot pass test cases 4 and 5. My code is below, including my own custom test cases that all execute and pass in under 5ms.
Basically I added a third dimension to each node's position that represents whether a wall has already been traversed or not. When analyzing each current node's neighbor, if it's a wall and the current node has a zero for its third coordinate, then moving to the wall and to a 1 on the third coordinate becomes an option. On paper, it works great. In my own IDE, it works great.
I'm starting to wonder if there's something in here that's Python 3 and not working correctly in foobar or something. I'd appreciate any help.
class Node():
def __init__(self, position):
self.position = position
self.gCost = 1
self.hCost = 0
self.fCost = 0
def __eq__(self, other):
return self.position == other.position
def solution(map):
startNode = Node((0, 0, 0))
endNode = Node((len(map[0]) - 1, len(map) - 1, 0))
openList = [startNode]
closedList = []
while openList:
currentNode = openList[0]
currentIndex = 0
for i in range(len(openList)):
if openList[i].fCost < currentNode.fCost:
currentNode = openList[i]
currentIndex = i
openList.pop(currentIndex)
closedList.append(currentNode)
if currentNode.position[0] == endNode.position[0] and currentNode.position[1] == endNode.position[1]:
return currentNode.gCost
for offset in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
neighborPosition = (currentNode.position[0] + offset[0], currentNode.position[1] + offset[1], currentNode.position[2])
if neighborPosition[0] < 0 or neighborPosition[0] >= len(map[0]) or neighborPosition[1] < 0 or neighborPosition[1] >= len(map):
continue
if map[neighborPosition[0]][neighborPosition[1]] == 1:
if currentNode.position[2] == 1:
continue
neighborPosition = (neighborPosition[0], neighborPosition[1], 1)
neighbor = Node(neighborPosition)
if neighbor in closedList:
continue
if neighbor in openList:
openNodeIndex = openList.index(neighbor)
if openList[openNodeIndex].gCost < currentNode.gCost + 1:
continue
openList.pop(openNodeIndex)
openList.append(neighbor)
else:
openList.append(neighbor)
neighbor.gCost = currentNode.gCost + 1
neighbor.hCost = endNode.position[0] - neighbor.position[0] + endNode.position[1] - neighbor.position[1]
neighbor.fCost = neighbor.gCost + neighbor.hCost
return -1
import time
start = time.time()
map1 = [[0, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0]]
sol1 = solution(map1)
print("Result: ", sol1, "Expected: ", 7)
map2 = [[0,1,0,0,0], [0,1,0,1,0], [0,1,0,1,0], [0,1,0,1,0], [0,0,0,1,0]]
sol2 = solution(map2)
print("Result: ", sol2, "Expected: ", 9)
map3 = [[0,0,0,0,0,0,1,0,0,0], [0,0,0,0,1,0,1,0,1,0], [0,0,0,0,1,0,1,0,1,0], [0,0,0,0,1,0,1,0,1,0], [0,0,0,0,1,0,1,0,1,0], [0,0,0,0,1,0,1,0,1,0], [0,0,0,0,1,0,1,0,1,0], [0,0,0,0,1,0,1,0,1,0], [0,0,0,0,1,0,1,0,1,0], [0,0,0,0,1,0,0,0,1,0]]
sol3 = solution(map3)
print("Result: ", sol3, "Expected: ", 19)
map4 = [[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]]
sol4 = solution(map4)
print("Result: ", sol4, "Expected: ", 11)
map5 = [[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]]
sol5 = solution(map5)
print("Result: ", sol5, "Expected: ", 7)
map6 = [[0,1,0], [0,1,0], [0,1,0]]
sol6 = solution(map6)
print("Result: ", sol6, "Expected: ", 5)
map7 = [[0,1,1,0,0,0,0,1,0,1,0,0,0,0,1,1,0,1,1,0], [0,1,1,0,1,1,0,1,0,1,0,1,1,0,1,1,0,1,1,0], [0,1,1,0,1,1,0,1,0,1,0,1,1,0,1,1,0,1,1,0], [0,1,1,0,1,1,0,1,0,1,0,1,1,0,1,1,0,1,1,0], [0,1,1,0,1,1,0,1,0,1,0,1,1,0,1,1,0,1,1,0], [0,1,1,0,1,1,0,1,0,1,0,1,1,0,1,1,0,1,1,0], [0,1,1,0,1,1,0,1,0,1,0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0,0,0,1,0,0,0,0,0,0],[0,1,0,1,0,1,0,1,0,0,0,1,1,1,0,1,1,1,1,1],[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,0],[1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1],[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,0,1,0,0],[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0],[0,1,0,1,0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,0],[0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,0,1,1,1,1],[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,0,1,1,0,0]]
sol8 = solution(map8)
print("Result: ", sol8, "Expected: ", 89)
end = time.time()
print("Time: ", end - start)
Edit: Quick update - converted the closedList to a set and now it solves my test cases in under 1ms, still fails Google's test cases 4 and 5 though.
So I figured it out. The line
if map[neighborPosition[0]][neighborPosition[1]] == 1:
had the x and y coordinates backwards. It should have been
if map[neighborPosition[1]][neighborPosition[0]] == 1:
In cases where the map was not square it was going out of bounds. Just needed to add a test case that wasn't square and figured it out pretty quick from there.

Reversing a list. Problem with appending to lists in Ruby

So, I've been trying to reverse a list in Ruby.
Here is the code:
def reverse(arr)
retval = []
arr.each do |e|
retval = [e] << retval[0..retval.length]
end
return retval
end
arr = [1, 2, 3, 4, 5]
res = reverse(arr)
puts "[" + res * ", " + "]"
The expected output is:
[5, 4, 3, 2, 1]
Result:
[5, 4, 3, 2, 1, ]
I believe [e] << retval[0..retval.length] does not append properly here. I think instead of, for example, [1] << [] = [1] I get [1] << [] = [1, []].
Any idea how do I fix this?
Note: Please do not suggest any other way how to reverse a list. Thank you :)
Never mind, I found the solution. It had simple yet vital mistake. I wrote + the concatenation operator instead of << and it fixed it. Here is the full code:
def reverse(arr)
retval = []
arr.each do |e|
retval = [e] + retval[0..retval.length]
end
return retval
end
arr = [1, 2, 3, 4, 5]
res = reverse(arr)
puts "[" + res * ", " + "]"

Sum of two sums in Ruby with two loops

If a pair of numbers in the array sums to zero, I want the positions of those two numbers. If no pair of numbers sums to zero, i should return nil.
The iteration not happening in my outer loop:
def two_sum(nums)
# puts(nums)
l = nums.length
i = 0
j = 1
while(i < l)
while(j < l)
puts(nums[i] + nums[j])
puts(nums[i])
puts(nums[j])
if(nums[i] + nums[j] == 0)
return ("[" + i.to_s + "," + j.to_s + "]")
puts("[" + i.to_s + "," + j.to_s + "]")
else
j = j + 1
end
end
i = i + 1
end
end
It's much simpler to use ranges and each; this makes the code much clearer and more concise:
#!/usr/bin/env ruby
def two_sum(nums)
(0...nums.length).each do |i|
((i+1)...nums.length).each do |j|
return [i, j] if nums[i] + nums[j] == 0
end
end
nil
end
p two_sum([1, 2, 3, -1, 4]) # [0, 3]
p two_sum([1, 2, 3]) # nil
p two_sum([]) # nil
The problem is that you set the value of j = 1 only at the beginning, but you need it reset for each outer iteration. Just move the j = 1 after the
while(i < l)
or even better: j = i + 1
As ✅ has answered you question, I would like to suggest an alternative:
def pair_sums_to_zero(arr)
h = arr.each_with_index.group_by { |n,_| n.abs }
return h[0].first(2).map(&:last) if h.key?(0) and h[0].size > 1
a = h.map { |k,v| v.uniq(&:first) }.find { |b| b.size == 2 }
a ? a.map(&:last) : nil
end
arr = [3,2,-4,-2,3,2]
pair_sums_to_zero arr
#=> [1,3]
The steps:
h = arr.each_with_index.group_by { |n,_| n.abs }
#=> {3=>[[3, 0], [3, 4]], 2=>[[2, 1], [-2, 3], [2, 5]], 4=>[[-4, 2]]}
h.key?(0) and h[0].size > 1
#=> false
c = h.map { |k,v| v.uniq(&:first) }
#=> [[[3, 0]], [[2, 1], [-2, 3]], [[-4, 2]]]
a = c.find { |b| b.size == 2 }
a ? a.map(&:last) : nil
#=> [[2, 1], [-2, 3]]
a ? a.map(&:last) : nil
#=> [1, 3]
Another example:
arr = [3,0,2,-4,-6,0,3,0,2]
pair_sums_to_zero arr
h = arr.each_with_index.group_by { |n,_| n.abs }
#=> {3=>[[3, 0], [3, 6]], 0=>[[0, 1], [0, 5], [0, 7]], 2=>[[2, 2], [2, 8]],
# 4=>[[-4, 3]], 6=>[[-6, 4]]}
h.key?(0) and h[0].size > 1
#=> true
h[0].first(2).map(&:last)
#=> [1, 5] (returned)

How to fix an Adam's method?

I've such errors:
Coordinate .. is not a floating-point number
and can't correctly fix it.
The program works correctly for a function 1 - t *y , but not for y*y*Exp[t] - 2*y.
I will be really happy if you tell me why and how to fix this problem.
ABM[a0_, b0_, \[Alpha]_, m0_] :=
Module[{a = a0, b = b0, F, j, k, m = m0, p},
h = (b - a)/m; T = Table[a, {m + 1}];
Y = Table[\[Alpha], {m + 1}];
For[j = 1, j <= 3, j++, Subscript[k, 1] = h*f[T[[j]], Y[[j]]];
Subscript[k, 2] = h*f[T[[j]] + h/2, Y[[j]] + Subscript[k, 1]/2];
Subscript[k, 3] = h*f[T[[j]] + h/2, Y[[j]] + Subscript[k, 2]/2];
Subscript[k, 4] = h*f[T[[j]] + h, Y[[j]] + Subscript[k, 3]];
Y[[j + 1]] = Y[[j]] + (1/6)*(Subscript[k, 1] + 2*Subscript[k, 2] +
2*Subscript[k, 3] + Subscript[k, 4]);
T[[j + 1]] = a + h*j; ];
Subscript[F, 0] = f[T[[1]], Y[[1]]]; Subscript[F, 1] =
f[T[[2]], Y[[2]]]; Subscript[F, 2] = f[T[[3]], Y[[3]]];
Subscript[F, 3] = f[T[[4]], Y[[4]]]; For[j = 4, j <= m, j++,
p = Y[[j]] + (h/24)*(-9*Subscript[F, 0] + 37*Subscript[F, 1] -
59*Subscript[F, 2] + 55*Subscript[F, 3]);
T[[j + 1]] = a + h*j;
p = Y[[j]] + (h/24)*(Subscript[F, 1] -
5*Subscript[F, 2] + 19*Subscript[F, 3] +
9*f[T[[j + 1]], p]);
Y[[j + 1]] = p; Subscript[F, 0] = Subscript[F, 1];
Subscript[F, 1] = Subscript[F, 2]; Subscript[F, 2] =
Subscript[F, 3];
Subscript[F, 3] = f[T[[j + 1]], Y[[j + 1]]]; ];
Return[Transpose[{T, Y}]]];
f[t_, y_] = y*y*Exp[t] - 2*y;
Print["Find numerical solutions to the D.E."];
Print["y' = ", f[t, y]];
n = 25;
pts1 = ABM[0, 8, 2., n];
Y1 = Y;
Needs["Graphics`Colors`"];
graph1 = ListPlot[pts1, PlotJoined -> True, PlotStyle -> Green,
PlotRange -> {{0, 10}, {0, 10}}];
Print["The Adams-Bashforth-Moulton solution for y' = ", f[t, y]];
Print["Using n = ", n + 1, " points."];
Print[pts1];
Print[""];
Print["The final value is y(5) = ", Subscript[y, n + 1], " = ",
Y[[n + 1]]];

Why doesn’t FieldExp (finite fields package) return a primitive element?

Needs["FiniteFields`"]
fld=GF[2,3]
GF[2,{1,0,1,1}]
PowerListQ[fld]
True
pe=FieldExp[fld,1]
FieldExp[GF[2,{1,0,1,1}],1]
PowerListQ doesn't seem to accept variable substitution:
Needs["FiniteFields`"]
fld = GF[2, 3];
PowerListQ[fld] = True;
FieldExp[fld, 1]
PowerListQ[GF[2, 3]] = True;
FieldExp[fld, 1]
This returns
FieldExp[GF[2, {1, 0, 1, 1}], 1]
and
{0, 1, 0} 2
which is the expected answer.
I tried PowerListQ[Evaluate[fld]] = True; to no avail.
ToExpression["PowerListQ[" <> ToString[fld] <> "]=True"] works though.
I.e.
Needs["FiniteFields`"]
fld = GF[2, 3];
ToExpression["PowerListQ[" <> ToString[fld] <> "]=True"];
FieldExp[fld, 1]
yields {0, 1, 0} 2

Resources