How can I sort a list/matrix in a function? - ti-basic

When I try to use SortA and SortD in a function:
Define test()=
Func
© Convoluted way of returning [0 1 2 4 5; 4 1 3 5 2]
Local a,b
a:=[1 5 2 0 4]
b:=[1 2 3 4 5]
SortA a,b
Return colAugment(a,b)
EndFunc
I get the error Invalid in a function or current expression. I think this is because SortA modifies variables and this isn't allowed in a function, only in a program. Is there a way to sort a list or matrix in this way in a function?

All you have to do is declare b as a local variable (as well as a):
Local a,b
And then it shouldn't return the error you mentioned.
I hope that helped!

The function SortA, SortD appears to work fine on the App calculator, and as a Program, but not with in a function.
Check this and correct a few mistakes
Regards
Code
Running it

While this doesn’t sort matrices, I made this function that sorts a list in ascending order. I don’t think it’s very efficient though as it just loops through the list and calls min, but my use case was only for small lists up to around 5 elements and I wanted it to be quick to type on my handheld calculator.
© Can't name it sorta due to the builtin
Define srta(xs)=
Func
Local ys,x,i,j,k,l0,l
l0:=dim(xs)
ys:={}
For i,l,l0
x:=min(xs)
ys:=augment(ys,{x})
l:=dim(xs)
For j,1,l
If xs[j]=x Then
© This splices the element at j (x) out of the list xs
xs:=seq(xs[k+piecewise(0,k<j,1)],k,1,l-1)
Exit
EndIf
EndFor
EndFor
Return ys
EndFunc
To sort it in descending order, replace min with max.

Related

N-step code for fibonacci OCAML

So I'm trying to code something for my class that will output an int list of the first k terms in an n-step fibonacci sequence.
So for those of you that don't know, an n step fibonacci sequence is when you add the n numbers before it to get the next one,
so for n=1 it'd be 1,1,1,1,1,...
n=2, it'd be 1,1,2,3,5,...
n=3 it'd be 1,1,2,4,7...
My approach was to start of with a base case, so
let rec n_step n k=
if k=1 then [1] else
if n=1 then 1::nacci n k-1 else
but now I'm stuck here. I know I need to iterate through and add up the terms in the list, but I'm not sure how to accomplish this.
I made a helper function sum
let rec sum lst =
match lst with
| [] -> 0
| h::t -> h + sum t
I was trying to make it selectively add the last n numbers of the list to get the next value but I got stuck on that as well
Thanks in advance!
This is homework so I'll only suggest some steps, not a complete solution:
if you come from an imperative background, try first an imperative solution such as a loop that prints the result instead of building a list and tying the recursion at once. You can store the required state in a global and gradually change that to pass parameters.
start with n=2, using a tuple instead of a list. It will be considerably easier to do that first, manually extend to fixed n=3 and fixed n=4 before using a list.
Applying these two pieces of advice, a first step might be:
let print_fib_2 () =
let previous_ref = ref (1, 1) in
for i = 0 to 10 do
let (a, b) = !previous_ref in
let next = a + b in
previous_ref := (next, a);
Printf.printf "%d\n" next
done
I'd first generalize to using changing n=2 to n=3: what happens to the pairs (a, b) and (next, a)? what does it mean in terms of lists?
By following baby steps from a working example you should be able to work to a solution.
I've figured it out using many helper functions.
So I've made a sum function that would sum up the values in a list
A gather function that would only take the n values from the entire list
and then in my original function, I used pattern matching for the k's such that if k=1, it would yield one and otherwise it would recurse. If it wasn't one I appended the next value using the helper

Operate on the y's of a {{x1,y1},{x2,y2},...{xn,yn}} list

I've been scratching my head and I can't figure out a way to conveniently apply an operation to the y values of a list of the form{{x1,y1},{x2,y2},...{xn,yn}}. The list is in this form for plotting with ListPlot[] mostly.
The type of operations I'd like to apply would include:
Mathematica Operations. Ex.: LowpassFilter[y's] (not point-by-point, I know)
Generic mathematic point-by-point operations. Ex: y's*10 + 2
I know I can transpose and then filpity-flop turn the list arround and then target each element, and then transpose back and flopity-flip and overwrite the original list. This becomes tiresome after dealing with each case. I bet there is a cleaver way to do this. Or what would be the best way to hold values in a list that can easily be plotted and manipulated?
Thanks
Map[{#[[1]],2+10 #[[2]]}&,{{x1,y1},{x2,y2},...{xn,yn}}]
MapAt[2+10#&,{{x1,y1},{x2,y2},...{xn,yn}},{All,2}]
if you need to operate on the 'y' list as a list, do like this:
Transpose#MapAt[LowpassFilter[#,1]&,
Transpose#{{x1,y1},{x2,y2},...{xn,yn}},2]
Suppose you named your list as l, i.e.
l={{x1,y1},{x2,y2},...{xn,yn}}
You can get all ys by:
ylist=l[[All,2]]
{#, 10 # + 2} & ### lst
{{x1, 2 + 10 x1}, {x2, 2 + 10 x2}, {xn, 2 + 10 xn}}

Scope of variables and the digits function

My question is twofold:
1) As far as I understand, constructs like for loops introduce scope blocks, however I'm having some trouble with a variable that is define outside of said construct. The following code depicts an attempt to extract digits from a number and place them in an array.
n = 654068
l = length(n)
a = Int64[]
for i in 1:(l-1)
temp = n/10^(l-i)
if temp < 1 # ith digit is 0
a = push!(a,0)
else # ith digit is != 0
push!(a,floor(temp))
# update n
n = n - a[i]*10^(l-i)
end
end
# last digit
push!(a,n)
The code executes fine, but when I look at the a array I get this result
julia> a
0-element Array{Int64,1}
I thought that anything that goes on inside the for loop is invisible to the outside, unless I'm operating on variables defined outside the for loop. Moreover, I thought that by using the ! syntax I would operate directly on a, this does not seem to be the case. Would be grateful if anyone can explain to me how this works :)
2) Second question is about syntex used when explaining functions. There is apparently a function called digits that extracts digits from a number and puts them in an array, using the help function I get
julia> help(digits)
Base.digits(n[, base][, pad])
Returns an array of the digits of "n" in the given base,
optionally padded with zeros to a specified size. More significant
digits are at higher indexes, such that "n ==
sum([digits[k]*base^(k-1) for k=1:length(digits)])".
Can anyone explain to me how to interpret the information given about functions in Julia. How am I to interpret digits(n[, base][, pad])? How does one correctly call the digits function? I can't be like this: digits(40125[, 10])?
I'm unable to reproduce you result, running your code gives me
julia> a
1-element Array{Int64,1}:
654068
There's a few mistakes and inefficiencies in the code:
length(n) doesn't give the number of digits in n, but always returns 1 (currently, numbers are iterable, and return a sequence that only contain one number; itself). So the for loop is never run.
/ between integers does floating point division. For extracting digits, you´re better off with div(x,y), which does integer division.
There's no reason to write a = push!(a,x), since push! modifies a in place. So it will be equivalent to writing push!(a,x); a = a.
There's no reason to digits that are zero specially, they are handled just fine by the general case.
Your description of scoping in Julia seems to be correct, I think that it is the above which is giving you trouble.
You could use something like
n = 654068
a = Int64[]
while n != 0
push!(a, n % 10)
n = div(n, 10)
end
reverse!(a)
This loop extracts the digits in opposite order to avoid having to figure out the number of digits in advance, and uses the modulus operator % to extract the least significant digit. It then uses reverse! to get them in the order you wanted, which should be pretty efficient.
About the documentation for digits, [, base] just means that base is an optional parameter. The description should probably be digits(n[, base[, pad]]), since it's not possible to specify pad unless you specify base. Also note that digits will return the least significant digit first, what we get if we remove the reverse! from the code above.
Is this cheating?:
n = 654068
nstr = string(n)
a = map((x) -> x |> string |> int , collect(nstr))
outputs:
6-element Array{Int64,1}:
6
5
4
0
6
8

Is working past the end of a slice idiomatic?

I was reading through Go's compress/flate package, and I found this odd piece of code [1]:
n := int32(len(list))
list = list[0 : n+1]
list[n] = maxNode()
In context, list is guaranteed to be pointing to an array with more data after. This is a private function, so it can't be misused outside the library.
To me, this seems like a scary hack that should be a runtime exception. For example, the following D code generates a RangeError:
auto x = [1, 2, 3];
auto y = x[0 .. 2];
y = y[0 .. 3];
Abusing slices could be done more simply (and also look more safe) with the following:
x := []int{1, 2, 3}
y = x[:2]
y = append(y, 4) // x is now [1, 2, 4] because of how append works
But both solutions seem very hacky and scary and, IMHO, should not work as they do. Is this sort of thing considered idiomatic Go code? If so, which of the the above is more idiomatic?
[1] - http://golang.org/src/pkg/compress/flate/huffman_code.go#L136
This is not abusing the slice, this is just perfectly using what a slice is : a window over an array.
I'll take this illustration from another related answer I made :
array : [0 0 0 0 0 0 0 0 0 0 0 0]
array : <---- capacity --->
slice : [0 0 0 0]
slice : <---- capacity --->
When the array is greater than the slice it's normal and standard to take a greater slice by extending one when you know you don't go out of the underlying array (which can be verified using cap()).
Regarding your buggy code you give as example, yes, it might be dangerous, but arrays and slices are among the most basic structures of the languages and you must understand them before you use them if you want to avoid such bugs. I personally think that any go coder should not only know the API but also what are slices.
In the code you link to, a short analysis shows that there is no possible overflow possible as list is created as
list := make([]literalNode, len(freq)+1)
and is later resized to count which can't be greater than len(freq) :
list = list[0:count]
One might have preferred a few more comments but as the function containing list = list[0 : n+1] is private and called from only one place, it might also be considered the balancing between comment verbosity and code obscurity sounds right. It's painful to have too much comments hiding the code and anybody in need to read this code is able to easily check there is no overflow just like I did.
It cannot be a run time exception because the language specification prescribes that the upper limit of the slice operation is the capacity of the slice, not its length.

How to change a negative number to zero in python without using decision structures

I have a program that determines the number of points you get per day, for 5 days from an event.
source code:
total=0
for x in range (5):
points=int(input('How many points did you get today?'))
total=total+points
print ('You got {0} points this event'.format(total))
My question is how do I get it to make any number below or equal to zero a 0 without using decision statements (if's, case's, i think while or for loop is not allowed either)
Can you use built-in functions? Because this is normally done using:
max(0, points)
>>> f=lambda a: (abs(a)+a)/2
>>> f(a)
0
>>> f(3)
3
>>> f(-3)
0
>>> f(0)
0
Since I don't see boolean operators as a restriction, you can use:
points * (points>0)

Resources