Summary and reverse - reverse

I'm just starting with FreeMarker and I didn't get the answer. Maybe somebody can help me?
I want to show: <#assign test = ["x","y","z"] /> in reverse direction as z,y,x using the list function but I don't know how to do it. If I have: <#assign ordercount = ["20","40","60"], how can I get the summary of all numbers as result using the list function?

Reverse:
<#assign test = ["x","y","z"] >
${test?reverse?join(", ")}
result: z, y, x
Summary:
<#function sum nums...>
<#local sum = 0>
<#list nums as num>
<#local sum += num>
</#list>
<#return sum>
</#function>
${sum(20, 40,60)}
result: 120

Reverse:
[#assign letters = ["x","y","z"]]
[#assign lettersReversed = []]
[#list letters as i]
[#assign lettersReversed += [letters[letters?size-1-i?index]]]
[/#list]
lettersReversed :["z","y","x"]
Sum:
[#assign numbers = ["20","40","60"]]
[#function sumStringNums input]
[#local sum = 0]
[#list input as i]
[#local sum += i?number]
[/#list]
[#return sum]
[/#function]
${sumStringNums(numbers)}
output: 120

Related

adding functions to self made calculator

Ok so I'm trying to make a working napier numeral calculator. I have gone through most of the steps I need to make it work. I need 2 more steps the function and converting it back to napier numbers. Currently I'm stuck on getting the functions to work. It just seems to skip that step. From what I can tell it should work and not be skipped. Could anyone tell me if I missed a step in the process of making the function.
def main():
response = 'y'
while response == 'y' or response == 'Y':
nap1 = getNapier()
num1 = napToInt(nap1)
print(num1)
nap2 = getNapier()
num2 = napToInt(nap2)
print(num1, num2)
operator = getOperator
result = doMath(num1, num2, operator)
response = input("Try another[y/n]")
def doMath(num1, num2, operator):
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "*":
answer = num1 * num2
else:
if operator == "/":
answer = num1 / num2
return doMath
def getOperator():
op = input("Enter operator: ")
while op not in "+-*/":
op = input("Error!!!! Enter operator: ")
return op
def napToInt(n):
result = 0
for ch in n:
result += 2 ** (ord(ch) - ord('a'))
return result
def getNapier():
nap = input("Enter Napier number: ")
while not nap.isalpha():
nap = input("Error!!! Enter Napier number: ")
return nap
main()
this is the result I get as you can see it gets the napier numbers and just stops
Enter Napier number: asdf
262185
Enter Napier number: adsf
262185 262185
Try another[y/n]
your line operator = getOperator should be operator = getOperator()

python function will not return value that is based on condition

I am new to this, and I am looking for help. I currently am stuck in a program I'm trying to complete. Here it is:
def printStock(stockList, stockPrice, p):
for i in range(len(stockPrice)):
if stockPrice[i] > p:
p = stockList[i]
print("The stocks with a higher value are:", p)
def searchStock(stockList, stockPrice, s):
for i in range(len(stockList)):
if s == stockList[i]:
s = stockPrice[i]
elif s != stockList[i]:
s = -1
return s
def mainFun():
stockList= []
stockPrice = []
l = 1
while l > 0:
stocks = str(input("Enter the name of the stock:"))
stockList += [stocks]
if stocks == "done"or stocks == 'done':
l = l * -1
stockList.remove("done")
else:
price = int(input("Enter the price of the stock:"))
stockPrice += [price]
l = l + 1
print(stockList)
print(stockPrice)
s = input("Enter the name of the stock you're looking for:")
searchStock(stockList, stockPrice, s)
p = s
printStock(stockList, stockPrice, p)
Every time I run the program to the end, it never returns the variable s for some reason. If i replace return with print, it always prints -1 instead of the stockPrice if its on the list. I also get an error saying "unorderable types int() > str()" regarding line 3. Basically the function printStock takes the three parameters and once the function is done it should print the names of the stocks higher than the value 'p'. The value of 'p' is the same as the value I get after calling searchStock function, but I cant seem to get it to work. Can someone please help me?
s is being returned from the function, but the return value is not being assigned to any variable on the outer scope.
Just replace
searchStock(stockList, stockPrice, s)
with
s=searchStock(stockList, stockPrice, s)
And everything should work as expected

Iterate over each row in matrix Octave

How do I iterate over each row in Z where Z is a 2 * m matrix:
6.1101,17.592
5.5277,9.1302
8.5186,13.662
How do I access each Z(i)(j) inside this loop?
For example:
for i = z
fprintf('Iterating over row: '+ i);
disp (i:1);
disp (i:2);
end
Would output:
Iterating over row: 1
6.1101
17.592
Iterating over row: 2
5.5277
9.1302
Iterating over row: 3
8.5186
13.662
If you use for i = z when z is a matrix, then i takes the value of the first column of z (6.1101; 5.5277; 8.5186), then the second column and so on. See octave manual: The-for-Statement
If you want to iterate over all elements you could use
z = [6.1101,17.592;5.5277,9.1302;8.5186,13.662]
for i = 1:rows(z)
for j = 1:columns(z)
printf("z(%d,%d) = %f\n", i, j, z(i,j));
endfor
endfor
which outputs:
z(1,1) = 6.110100
z(1,2) = 17.592000
z(2,1) = 5.527700
z(2,2) = 9.130200
z(3,1) = 8.518600
z(3,2) = 13.662000
But keep in mind that for loops are slow in octave so it may be desirable to use a vectorized method. Many functions can use a matrix input for most common calculations.
For example if you want to calculate the overall sum:
octave> sum (z(:))
ans = 60.541
Or the difference between to adjacent rows:
octave> diff (z)
ans =
-0.58240 -8.46180
2.99090 4.53180
You can transpose the matrix first and then do a for statement like so:
for i = z'
disp(i(1))
disp(i(2))
end
Although in this case you won't have an index stating which row you are using

Tweaking a Function in Python

I am trying to get the following code to do a few more tricks:
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.answerLabel = Label(self, text="Output List:")
self.answerLabel.grid(row=2, column=1, sticky=W)
def psiFunction(self):
j = int(self.indexEntry.get())
valueList = list(self.listEntry.get())
x = map(int, valueList)
if x[0] != 0:
x.insert(0, 0)
rtn = []
for n2 in range(0, len(x) * j - 2):
n = n2 / j
r = n2 - n * j
rtn.append(j * x[n] + r * (x[n + 1] - x[n]))
self.answer = Label(self, text=rtn)
self.answer.grid(row=2, column=2, sticky=W)
if __name__ == "__main__":
root = Tk()
In particular, I am trying to get it to calculate len(x) * j - 1 terms, and to work for a variety of parameter values. If you try running it you should find that you get errors for larger parameter values. For example with a list 0,1,2,3,4 and a parameter j=3 we should run through the program and get 0123456789101112. However, I get an error that the last value is 'out of range' if I try to compute it.
I believe it's an issue with my function as defined. It seems the issue with parameters has something to do with the way it ties the parameter to the n value. Consider 0123. It works great if I use 2 as my parameter (called index in the function) but fails if I use 3.
EDIT:
def psi_j(x, j):
rtn = []
for n2 in range(0, len(x) * j - 2):
n = n2 / j
r = n2 - n * j
if r == 0:
rtn.append(j * x[n])
else:
rtn.append(j * x[n] + r * (x[n + 1] - x[n]))
print 'n2 =', n2, ': n =', n, ' r =' , r, ' rtn =', rtn
return rtn
For example if we have psi_j(x,2) with x = [0,1,2,3,4] we will be able to get [0,1,2,3,4,5,6,7,8,9,10,11] with an error on 12.
The idea though is that we should be able to calculate that last term. It is the 12th term of our output sequence, and 12 = 3*4+0 => 3*x[4] + 0*(x[n+1]-x[n]). Now, there is no 5th term to calculate so that's definitely an issue but we do not need that term since the second part of the equation is zero. Is there a way to write this into the equation?
If we think about the example data [0, 1, 2, 3] and a j of 3, the problem is that we're trying to get x[4]` in the last iteration.
len(x) * j - 2 for this data is 10
range(0, 10) is 0 through 9.
Manually processing our last iteration, allows us to resolve the code to this.
n = 3 # or 9 / 3
r = 0 # or 9 - 3 * 3
rtn.append(3 * x[3] + 0 * (x[3 + 1] - x[3]))
We have code trying to reach x[3 + 1], which doesn't exist when we only have indices 0 through 3.
To fix this, we could rewrite the code like this.
n = n2 / j
r = n2 - n * j
if r == 0:
rtn.append(j * x[n])
else:
rtn.append(j * x[n] + r * (x[n + 1] - x[n]))
If r is 0, then (x[n + 1] - x[n]) is irrelevant.
Please correct me if my math is wrong on that. I can't see a case where n >= len(x) and r != 0, but if that's possible, then my solution is invalid.
Without understanding that the purpose of the function is (is it a kind of filter? or smoothing function?), I prickled it out of the GUI suff and tested it alone:
def psiFunction(j, valueList):
x = map(int, valueList)
if x[0] != 0:
x.insert(0, 0)
rtn = []
for n2 in range(0, len(x) * j - 2):
n = n2 / j
r = n2 - n * j
print "n =", n, "max_n2 =", len(x) * j - 2, "n2 =", n2, "lx =", len(x), "r =", r
val = j * x[n] + r * (x[n + 1] - x[n])
rtn.append(val)
print j * x[n], r * (x[n + 1] - x[n]), val
return rtn
if __name__ == '__main__':
print psiFunction(3, [0, 1, 2, 3, 4])
Calling this module leads to some debugging output and, at the end, the mentionned error message.
Obviously, your x[n + 1] access fails, as n is 4 there, so n + 1 is 5, one too much for accessing the x array, which has length 5 and thus indexes from 0 to 4.
EDIT: Your psi_j() gives me the same behaviour.
Let me continue guessing: Whatever we want to do, we have to ensure that n + 1 stays below len(x). So maybe a
for n2 in range(0, (len(x) - 1) * j):
would be helpful. It only produces the numbers 0..11, but I think this is the only thing which can be expected out of it: the last items only can be
3*3 + 0*(4-3)
3*3 + 1*(4-3)
3*3 + 2*(4-3)
and stop. And this is achieved with the limit I mention here.

How to perform a conditional assignment on each element of the vector

I have a function like this:
y=-2 with x<=0
y=-2+3x^2 with 0=1
I need to compute this function on each element of the 1D matrix, without using a loop.
I thought it was possibile defining a function like this one:
function y= foo(x)
if x<=0
y=-2;
elseif x>=1
y=1;
else
y= -2+3*x.^2;
end
end
But this just produces a single result, how to operate on all elements? I know the . operator, but how to access the single element inside an if?
function b = helper(s)
if s<=0
b=-2;
elseif s>=1
b=1;
else
b= -2+3*s^2;
end
end
Then simply call
arrayfun(#helper, x)
to produce the behaviour you want of your function foo.
Another approach which doesn't need arrayfun() would be to multiply by the conditions:
y = -2*(x <= 0) + (-2+3*x.^2).*(x < 1).*(x > 0) + (x >= 1)
which you could also make a function. This will accept vector inputs for x e.g.
x = [1 4 0 -1 0.5];
y = -2*(x <= 0) + (-2+3*x.^2).*(x < 1).*(x > 0) + (x >= 1)
outputs
y =
1.0000 1.0000 -2.0000 -2.0000 -1.2500