Translating from Maple to Mathematica - wolfram-mathematica

Sorry if this question doesn't fit the site well... I have been trying translate a bit of Maple-code into Mathematica. I don't know Maple at all but I do know some Mathematica. I really don't know what I am doing so I wonder if someone could help me just a bit:
b:= proc(n, s) local sn, m;
if n<1 then 1
else sn:= [s[], n]; m:= nops(sn);
`if` (m*(m-1)/2 = nops (({seq (seq (sn[i]-sn[j],
j=i+1..m), i=1..m-1)})), b(n-1, sn), 0) +b(n-1, s)
fi
end:
a:= proc(n) a(n):= b(n-1, [n]) +`if` (n=0, -1, a(n-1)) end:
seq(a(n), n=1..30);
I think I understand everything except
sn:= [s[], n];
but I'm not sure. Thanks in advance!

The indexing call s[] returns the sequence of the entries of s if s is a list or a set.
For s of type list (in particular) the call s[] behaves like the call op(s). (Note that this similarity in behavior is true for lists, sets, and sequences. But it's not true for all types.)
L:=[2,4,7]:
L[];
2, 4, 7
op(L);
2, 4, 7
[L[], 5];
[2, 4, 7, 5]
So [s[], n] takes list s and creates a new list. The new list, which gets assigned to sn, contains the entries of list s followed by n.

Related

How can I improve my "rotate (roll / cyclic permutation) array" solution?

I am doing some stuff on leetcode and came up with solution it works fine but some cases.
Here is the problem itself:
But in case like this it doesn't:
It doesn't make sense how can I rotate elements if k is bigger than length of array.
If you have any idea how to improve this solution I would be grateful
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums) > k:
self.swap(nums, 0, len(nums)-1)
self.swap(nums, 0,k-1)
self.swap(nums, k, len(nums)-1)
def swap(self, nums, start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start+=1
end-=1
In order to understand why this doesn't work for the cases where k is larger than the array length, let me try to explain some of the logic behind rotating by such values of k.
The modulo operator, % will be useful. For example, if an array is 5 long, and you want to rotate by 5, you end up with the same array. So technically, you'd optimally want to rotate by 0. This is where the % operator comes into play. 5 % 5 = 0. If we want to rotate an array length 5 by 7 spots, we would end up with the same thing as rotating the array by 2, and it turns out that 7 % 5 = 2. Do you see where I am going with this?
This also holds true if the value of k is less than the length of the array. Say we want to rotate an array length 5 by 3, we do 3 % 5 = 3.
So for any rotation of amount k and array length L, optimization rotation amount n is equivalent to n = k % L.
You should modify your code at the beginning of your rotate method to adjust the rotation amount:
k = k % L
and use this value to rotate the correct amount.
The fastest and cleanest solution by far and large is:
def rotate_right(items, shift):
shift = -shift % len(items)
return items[shift:] + items[:shift]
ll = [i + 1 for i in range(7)]
# [1, 2, 3, 4, 5, 6, 7]
rotate_right(ll, 3)
# [5, 6, 7, 1, 2, 3, 4]
rotate_right([1, 2], 3)
# [2, 1]
of course, short of using numpy.roll() or itertools.cycle().

Is this an example of efficiency versus maintainability and readability? List Comprehension Python

I was doing a leet code problem called two sum, which is below:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
The code I wrote is:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
return [num for num in nums if (target-num) in nums and (target-num) != num]
Is this considered too abstruse? Are there faster ways to accomplish this task without losing out on readability? To me this seems legible and easy to understand but I would like a someone else to check.
I understand the caveats of the argument of efficiency vs. readability: and I am not trying to make a program more efficient. This is purely an educational question for my own benefit (and ego I suppose); I just want to know if this is the preferred method of attack.
Thanks in advance!

(Any Language) Find all permutations of elements in a vector using swapping

I was asked this question in a Lab session today.
We can imagine a vector containing the elements 1 ... N - 1, with a length N. Is there an algorithmic (systematic) method of generating all permutations, or orders of the elements in the vector. One proposed method was to swap random elements. Obviously this would work provided all previously generated permutations were stored for future reference, however this is obviously a very inefficient method, both space wise and time wise.
The reason for doing this by the way is to remove special elements (eg elements which are zero) from special positions in the vector, where such an element is not allowed. Therefore the random method isn't quite so ridiculous, but imagine the case where the number of elements is large and the number of possible permutations (which are such that there are no "special elements" in any of the "special positions") is low.
We tried to work through this problem for the case of N = 5:
x = [1, 2, 3, 4, 5]
First, swap elements 4 and 5:
x = [1, 2, 3, 5, 4]
Then swap 3 and 5:
x = [1, 2, 4, 5, 3]
Then 3 and 4:
x = [1, 2, 5, 4, 3]
Originally we thought using two indices, ix and jx, might be a possible solution. Something like:
ix = 0;
jx = 0;
for(;;)
{
++ ix;
if(ix >= N)
{
ix = 0;
++ jx;
if(jx >= N)
{
break; // We have got to an exit condition, but HAVENT got all permutations
}
}
swap elements at positions ix and jx
print out the elements
}
This works for the case where N = 3. However it doesn't work for higher N. We think that this sort of approach might be along the right lines. We were trying to extend to a method where 3 indexes are used, for some reason we think that might be the solution: Using a 3rd index to mark a position in the vector where the index ix starts or ends. But we got stuck, and decided to ask the SO community for advice.
One way to do this is to, for the first character e:
First recurse on the next element
Then, for each element e2 after e:
Swap e and e2
Then recurse on the next element
And undo the swap
Pseudo-code:
permutation(input, 0)
permutation(char[] array, int start)
if (start == array.length)
print array
for (int i = start; i < array.length; i++)
swap(array[start], array[i])
permutation(array, start+1)
swap(array[start], array[i])
With the main call of this function, it will try each character in the first position and then recurse. Simply looping over all the characters works here because we undo each swap afterwards, so after the recursive call returns, we're guaranteed to be back where we started.
And then, for each of those recursive calls, it tries each remaining character in the second position. And so on.
Java live demo.

Simply Pseudocode Question

I'm new to psuedocode, and I'm having trouble putting all the pieces together:
Here is the definition of a function named foo whose inputs are two integers and an array of integers a[1] ... a[n].
1 Foo(k,m, a[1],...,a[n])
2 if (k < 1 or m > n or k > m) return 0
3 else return a[k] + Foo(k+1,m,a[1],...,a[n])
Suppose that the input integers are k=2 and m=5 and the input array contains [5, 6, 2, 3, 4, 8, 2]. What value does Foo return? Using summation notation, give a general formula for what Foo computes.
This one is making my head hurt. Here's what I did so far:
Line 2 has three conditional statements:
If k<1 // if 2<1..this is false
If m>n // if 5 is greater than the amount of values in the array, which is 7, so this is false
If k>m // if 2>5, this is false
So this function will display line 3. Line 3 says:
return a[k] which is a[2] which is the second value of the array, which is 6. So take 6 and add it to (2+1, 5, a[1].....,a[n])
Is what I have done correct up there? If so, how would I know what a[n] is? Am I supposed to be finding that? What would be the final result of all this?
Simple answer: that function returns the sum of all the numbers a[k], a[k+1], ... a[m].
What you're doing is correct so far. The "n" is just a placeholder meaning the last element of the array. So if your input array is {5,6,2,3,4,8,2}, n = 7 (cause your have seven elements), and a[n] = 2.
But why it returns the sum of all numbers a[k], a[k+1], ... a[m], you should find out for yourself. Just continue with your analysis. :)
So take 6 and add it to (2+1, 5,
a[1].....,a[n])
Take 6 and add it to Foo(2+1, 5, a[1].....,a[n]). It's a recursive function. You have to evaluate the function again with k=3 and m=5.
I think you are confused because your pseudocode looks like real code to me. I may be wrong, but we are taught to write pseudocode differently, using plain English phrases.

Problem coming up with an array function

Let's say I have an increasing sequence of integers: seq = [1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 4 ... ] not guaranteed to have exactly the same number of each integer but guaranteed to be increasing by 1.
Is there a function F that can operate on this sequence whereby F(seq, x) would give me all 1's when an integer in the sequence equals x and all other integers would be 0.
For example:
t = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4]
F(t, 2) = [0, 0, 0, 0, 1, 1, 0, 0, 0, 0]
EDIT: I probably should have made it more clear. Is there a solution where I can do some algebraic operations on the entire array to get the desired result, without iterating over it?
So, I'm wondering if I can do something like: F(t, x) = t op x ?
In Python (t is a numpy.array) it could be:
(t * -1) % x or something...
EDIT2: I found out that the identity function I(t[i] == x) is acceptable to use as an algebraic operation. Sorry, I did not know about identity functions.
There's a very simple solution to this that doesn't require most of the restrictions you place upon the domain. Just create a new array of the same size, loop through and test for equality between the element in the array and the value you want to compare against. When they're the same, set the corresponding element in the new array to 1. Otherwise, set it to 0. The actual implementation depends on the language you're working with, but should be fairly simple.
If we do take into account your domain, you can introduce a couple of optimisations. If you start with an array of zeroes, you only need to fill in the ones. You know you don't need to start checking until the (n - 1)th element, where n is the value you're comparing against, because there must be at least one of the numbers 1 to n in increasing order. If you don't have to start at 1, you can still start at (n - start). Similarly, if you haven't come across it at array[n - 1], you can jump n - array[n - 1] more elements. You can repeat this, skipping most of the elements, as much as you need to until you either hit the right value or the end of the list (if it's not in there at all).
After you finish dealing with the value you want, there's no need to check the rest of the array, as you know it'll always be increasing. So you can stop early too.
A simple method (with C# code) is to simply iterate over the sequence and test it, returning either 1 or 0.
foreach (int element in sequence)
if (element == myValue)
yield return 1;
else
yield return 0;
(Written using LINQ)
sequence.Select(elem => elem == myValue ? 1 : 0);
A dichotomy algorithm can quickly locate the range where t[x] = n making such a function of sub-linear complexity in time.
Are you asking for a readymade c++, java API or are you asking for an algorithm? Or is this homework question?
I see the simple algorithm for scanning the array from start to end and comparing with each. If equals then put as 1 else put as 0. Anyway to put the elements in the array you will have to access each element of the new array atleast one. So overall approach will be O(1).
You can certainly reduce the comparison by starting a binary search. Once you find the required number then simply go forward and backward searching for the same number.
Here is a java method which returns a new array.
public static int[] sequence(int[] seq, int number)
{
int[] newSequence = new int[seq.length];
for ( int index = 0; index < seq.length; index++ )
{
if ( seq[index] == number )
{
newSequence[index] = 1;
}
else
{
newSequence[index] = 0;
}
}
return newSequence;
}
I would initialize an array of zeroes, then do a binary search on the sequence to find the first element that fits your criteria, and only start setting 1's from there. As soon as you have a not equal condition, stop.
Here is a way to do it in O(log n)
>>> from bisect import bisect
>>> def f(t, n):
... i = bisect(t,n-1)
... j = bisect(t,n,lo=i) - i
... return [0]*i+[1]*j+[0]*(len(t)-j-i)
...
...
>>> t = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4]
>>> print f(t, 2)
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0]

Resources