How to convert a .reduce function of Javascript to Python? - javascript

I am reading a javascript source and I need to convert it to Python.
Here is the code, since I am just a beginner, I dont get .reduce() function at all
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
Here is what I have tried so far
def bin2dec(num):
listNum = list(num)
listNum = map(int, listNum)
x = listNum[-1]
listNum.reverse()
for i in range (len(listNum)):
if listNum[i] == 1:
x = x + 2**listNum[i]
else:
x = x
return x
But it is not correct.

Normal Equivalence
Javascript parseInt(x, 2)
Python int(x, 2)
Using Same Method as Posted Code
from functools import reduce
import math
def bin2dec(s):
return reduce(lambda x, y_i: x + int(math.pow(2, y_i[0])) if y_i[1] == '1' else x,
enumerate(reversed(s)),
0)
Test
print(bin2dec('110')) # outut: 6
Explanation
reversed(s) to replace Javascript num.split('').reverse()
Python's reduce function from functools has signature reduce(function, iterable[, initializer])
Use Python lambda function in place of Javascript's function(x, y, i){... (1st argument)
Javascript reduce provide current value and current index y, i
Python only provides current value, so we use enumerate(..) on values array to convert to current index, current value pairs (2nd argument)
y_i are value tuples, with y_i[0] = index and y_i[1] the value
use 0 as initializer (last argument in reduce)
int to convert the value of math.pow from float to integer
Python if else expression in place of Javascript's ? ternary operator
Simpler Python Code than Using Reduce
def bin2dec(s):
return sum((0, 2**i)[y == '1'] for i, y in enumerate(s[::-1]))

You can just use the built-in int function:
int("010010", 2)
>>> 18
That said I found a pretty interesting alternative approach using js2py.
You can feed it the whole js function as a string, allowing you to effectively use js inside python:
import js2py
bin2dec = js2py.eval_js("""
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
""")
bin2dec("010010")
>>> 18
Install with pip install js2py
You made a lot of mistakes with your attempt, the map function returns an iterator, not a list. Generally, just avoid map and filter and just use a list comprehension instead.
You also raised 2 to the power of the value (1 or 0) when it should have been the index.
Here's a working version of your example:
def bin2dec(num):
listNum = [int(n) for n in num]
total = 0
listNum.reverse()
for i, n in enumerate(listNum):
if n == 1:
total += 2 ** i
return total

Related

Variable reassignment with chained booleans or ternary operator [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
To clarify:
This is purely for experimental purposes, to learn the quirks, odds and ends of a new (to me) language. I would of course write it readable if I ever were to share this code with anyone else. :-)
I have a function someFunction(x), and two global variables:
let m = 2;
let e = 5;
Inside the function, I want to check if x == m. If this is true, I'd like to pass m to a side function call (sideFunction(m)), then reassign x to e to complete someFunction.
This does work as expected:
const someFunction = x => {
if (x == m) {
sideFunction(m);
x = e;
}
doOtherStuffWith(x);
}
However, I'd like to shorten it, preferably to one line. This is also to understand more about ternaries and/or boolean chaining.
I have tried these two methods:
// Boolean chaining
const someFunction = x => {
x == m && sideFunction(m) && (function () {x = e})();
doOtherStuffWith(x);
}
This does not work, presumably because the assignment x = e only applies to the x in the local scope of the inner, anonymous function...?
// Ternary operator
const someFunction = x => {
x = (x == m && sideFunction(m)) ? e : x;
doOtherStuffWith(x);
}
This does not work, presumably because sideFunction(m) doesn't actually get called, for some reason...?
How can I fix these to make them work?
Alternatively, are there other, elegant ways to perform this check/call/reassignment without a full multi-line if block?
Thank you very much!
The problem with
x == m && sideFunction(m) && (function () {x = e})();
is that && evaluates left-to-right, and will stop as soon as the first falsey value is found. Unless sideFunction returns something explicitly truthy, the third IIFE:
(function () {x = e})()
will never run, resulting in x never being reassigned.
x is local in that function. If you can get the function to run, it will reassign x as desired.
You could use the comma operator:
x == m && (sideFunction(m), x = e);
Similarly
x = (x == m && sideFunction(m)) ? e : x;
won't work because sideFunction would have to return something truthy for the left side of the conditional to evaluate truthily - otherwise, x will be assigned to x, no change.
All this said - I'd highly recommend not doing any of these. Your first approach is much more readable, and readability is much more important than line conservation.
You could take a compound expression with a comma operator and do not care about the result value of sideFunction.
const fn = x => (x == m && (sideFunction(m), x = e), doOtherStuffWith(x));
The comma operator , can be used to chain expressions and return the last one e.g.,
var x = (1 + 2, 10 + 2, 100 + 2);
x;
//=> 102
We can use it to evaluate sideFunction(m) and return e: (sideFunction(m), e).
Since you always want to execute doOtherStuffWith you only need to work out whether to give it e or the original x:
const someFunction = x => doOtherStuffWith(x == m ? (sideFunction(m), e) : x);

Longest common subsequence (Why does this recursive solution not work?)

Trying to write a similar recursive solution to the one described on: http://www.geeksforgeeks.org/longest-common-subsequence/ but it does not work. It outputs one. Anyone have an idea of why?
LCS_seq_req = (str1, str2) => {
m=str1.length;
n=str2.length;
str1_cut = str1.slice(0, m-1)
str2_cut = str2.slice(0, n-1)
if (m===0 || n===0) {
return 0
}
else if (str1.slice(m-1, m) === str2.slice(n-1, n) ) {
return LCS_seq_req(str1_cut, str2_cut) + 1
} else {
res_1 = LCS_seq_req(str1_cut, str2)
res_2 = LCS_seq_req(str1,str2_cut)
return Math.max(res_1, res_2)
}
}
LCS_seq_req("AGGTAB", "GXTXAYB")
In JavaScript, unlike (say) Python, assigning to a variable inside a function does not implicitly declare it as a local variable. Instead, you need to explicitly declare it using the var keyword; otherwise you get a global variable.
More specifically, your problem is that this line:
res_1 = LCS_seq_req(str1_cut, str2)
has the side-effect of mutating the global variable str2_cut, causing this line:
res_2 = LCS_seq_req(str1,str2_cut)
to compute the wrong value. If you add var in the right places, you'll get the right answer.
Incidentally, Eric Lippert has written a blog post, https://ericlippert.com/2014/03/05/how-to-debug-small-programs/, which gives very good advice for how to debug this sort of problem on your own.
I looked at the Naive recursive Python implementation of LCS problem you give and converted Python code into JS code. Hope it will help.
LCS_seq_req = (str1, str2, m, n) => {
if(m == 0 || n == 0)
return 0;
else if(str1.charAt(m-1) === str2.charAt(n-1))
return 1 + LCS_seq_req(str1, str2, m-1, n-1);
else
return Math.max(LCS_seq_req(str1, str2, m, n-1), LCS_seq_req(str1, str2, m-1, n));
}
var X = "AGGTAB";
var Y = "GXTXAYB";
console.log(LCS_seq_req(X , Y, X.length, Y.length)); //6

Currying in Scala like JavaScript

Im new to functional programming in Scala and i'd like to know how to achieve the concept of currying in Scala. Below i have given an example of currying in JavaScript and I'd like to know the Scala equivalent of the same code.
var add = function(x){
return function(y){
return x + y;
};
};
console.log(add(1)(2));
var increment = add(1);
var addTen = add(10);
increment(2); //3
addTen(2); //12
Any Help would be appreciated :)
Let's first rewrite your example in more modern ECMAScript:
const add = x => y => x + y;
The Scala equivalent is very similar, it looks almost like this, the only difference is the val instead of const (although we could actually use var in both cases, and make the code truly identical):
// almost correct, but doesn't compile
val add = x => y => x + y
Except that doesn't work because Scala doesn't know what the types are, so we have to help just a little bit by either declaring the types of x and y, so Scala can properly infer the type of add or declare the type of add, so Scala can properly infer the types of the functions:
val add = (x: Int) => (y: Int) => x + y
// or
val add: Int => Int => Int = x => y => x + y
Scala also allows us to write them with a proper fat arrow if we want to:
val add = (x: Int) ⇒ (y: Int) ⇒ x + y
// or
val add: Int ⇒ Int ⇒ Int = x ⇒ y ⇒ x + y
So, as you can see, apart from the type declarations, the code is actually identical.
println(add(1)(2)) // 3
val increment = add(1)
val addTen = add(10)
increment(2) //=> 3
addTen(2) //=> 12
There is, however, another kind of currying in Scala, that is actually built into the language. In Scala, methods (which are different from functions) can have zero or more parameter lists, unlike most other languages (including ECMAScript) where there is always exactly one (potentially empty) parameter list. Methods that are defined with multiple parameter lists are called "curried" methods:
// this is a *method*, not a *function*, and thus different from the OP's example!
def addMeth(x: Int)(y: Int) = x + y
In Scala, we can convert a method into a function using η-expansion; this is written by placing an underscore after the name of the method:
// this converts the method `addMeth` into an anonymous function
// and assigns it to the variable `addFunc`
val addFunc = addMeth _
Now we can do the same things we did above using our curried addFunc function:
println(addFunc(1)(2)) // 3
val increment = addFunc(1)
val addTen = addFunc(10)
increment(2) //=> 3
addTen(2) //=> 12
But we can also use our addMeth method directly:
println(addMeth(1)(2)) // 3
val increment = addMeth(1) _
val addTen = addMeth(10) _
increment(2) //=> 3
addTen(2) //=> 12
So, unlike ECMAScript, Scala actually has a language built-in concept of currying, but
not for functions, only for methods and
not based on individual parameters but on parameter lists
Here it is:
def add(x:Int)(y:Int) = x+y
def increment = add(1) _
def addTen = add(10) _
val three = add(1)(2)
val four = increment(3)

Range using recursion, how to output a new array Javascript

How do you output a new array using recursion without declaring an empty array outside of the function? Another way of doing it will be creating an inner function and then return newFunction(), but it is not allowed as the task is to call the function itself. Here's what I have so far:
var newArr=[];
var range = function(x, y) {
if(x === y-1){
return newArr;
}
if(x < y){
newArr.push(x+1);
newArr = range(x+1,y);
}
else{
newArr.push(x-1);
newArr = range(x-1,y);
}
return newArr;
};
range(2,10) //[3,4,5,6,7,8,9]
So the key to this kind of thinking is understanding that you should be creating a lot of arrays.
Looking at a slightly different example...
A factorial is a number which goes backwards, through positive integers, multiplying each term with the term below it, and is written like 5!.
These are helpful when you find yourself asking questions like:
"How many permutations of ____ are there?"
"Given these 5 things, how many permutations can I arrange them in, from left to right?"
5! // =>
5 x 4 x 3 x 2 x 1 // =>
120
You could see how we could build a loop and set a variable for a counter, and a variable for the total, and multiply the current total by the current value of the counter we're decrementing.
But instead of doing that, we can try to use recursion.
First, think about how we could simplify that 5 x 4 x ... into one repeated step.
Really, 2! is 2 x 1. 3! is 3 x 2 x 1, which happens to be 3 x 2!.
So the general case might be something like: n! == n x (n - 1)!
So I might write a generalized function which does something like this:
// DO NOT RUN THIS FUNCTION!
function factorial (n) {
return n * factorial(n - 1);
}
So if I run factorial(5) and use my imagination, we can see that the program is doing something like:
factorial(5)
=> return 5 * factorial(5-1)
=> return 4 * factorial(4-1)
=> return 3 * factorial(3-1)
=> ...
Can you see any problems with the function as-is?
I said at the beginning that factorials (in this simplified case) are over positive integers.
How does my function know to stop when the integers stop being positive?
It doesn't, currently. Which is why the above implementation attempts to run forever, and will freeze the browser, while it tries to, until it gets thousands or tens of thousands of functions deep, before it says that you've reached the maximum depth of the call stack and explodes.
What we really need is a condition or a set of conditions, which we use to determine when we're done.
This is a base-case.
if (shouldStop(n)) {
return defaultValue;
}
Or in our case:
function factorial (n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
Now, when we run the function, we have:
factorial(5)
=> 5 * factorial(5 - 1)
=> 4 * factorial(4 - 1)
=> 3 * factorial(3 - 1)
=> 2 * factorial(2 - 1)
=> 1
=> 2 * 1
=> 3 * 2
=> 4 * 6
=> 5 * 24
=> 120
This is recursion.
And because of where the call is (returned at the very end of whatever branch you're in) it's a special kind of recursion (tail recursion), which allows some languages to optimize the code, replacing the function call with the contents of the function call, and thus skip adding to the call-stack like the first version (future versions of JS will support this power).
In more modern JS, I might rewrite it to look something like
const factorial = n => n <= 1 ? 1 : factorial(n - 1);
So now, what about other cases?
Well, sometimes, you need to make sure you're passing more things in.
Think about what your problem is, and what kinds of counters or flags or collectors you need, in order to do your job.
Here's one:
function makeNumberString (current, max, initialString) {
var str = initialString || ""; // maybe I don't have one yet
var currentString = str.concat(current.toString());
if (current > max) {
return initialString;
}
return makeNumberString(current + 1, max, currentString);
}
makeNumberString(0, 9); // "0123456789"
There are other ways of filling that function out, to make it do the same thing.
Note that currentString there is always a brand new string, made by joining the string that I was given with the new value I was passed. I'm not actually modifying the original string, but creating a new copy [HINT!!].
I hope that helps you.
you can simply do like this;
var range = (x,y,a=[]) => (++x < y && (a = range(x,y,a.concat(x))),a),
arr = range(2,10);
console.log(arr);
Note that the returned array is a parameter of the function and is passed to successive recursive calls.
There are many ways to skin this cat.
The simple way: create an array with the first value in it, then
concatenate the remaining values to it.
var range = function(x,y){
return x+1 >= y ? [] : [x+1].concat(range(x+1, y));
}
console.log(JSON.stringify(range(1, 10)));
The array is being constructed from right to left. Notice how the
recursive call to range is not the last thing the function does
before it returns: concatenation of the array follows.
We can also rewrite the function to be tail recursive with an accumulator as a parameter.
var range2 = function(x,y,a){
a = a || [];
return x+1 >= y ? a : range2(x+1, y, a.concat(x+1));
}
console.log(JSON.stringify(range2(1, 10)));
Now the call to range2 is the last thing the function does before
it returns. ES6 compliant JS engines are required to
optimise
calls in tail position (in strict mode) by discarding the execution
context from the stack.
Notice how we're now constructing the array from left to right.
You can avoid the extra parameter by using a helper function.
I've used an inner function, but it doesn't have to be.
var range3 = function(x,y){
var r = function(x,y,a){
return x+1 >= y ? a : r(x+1, y, a.concat(x+1));
}
return r(x, y, []);
}
console.log(JSON.stringify(range3(1, 10)));
Tail recursive using continuation passing style.
var range4 = function(x,y){
var r = function(x,y,c){
return x+1 >= y ? c([]) : r(x+1, y, function(a){
return c([x+1].concat(a));
});
}
return r(x, y, function(a){return a;});
}
console.log(JSON.stringify(range4(1, 10)));
Notice the similarity with the original range: the array is
constructed in reverse. This is trickier to get your head around and
may be something you never need, but it doesn't hurt to be aware of
it.
Try this:
function rangeRecursive(start, end) {
if(start === end){
return end;
} else if(start > end){
return [];
} else {
return [start].concat(rangeRecursive(++start, end));
}
}
console.log(rangeRecursive(4, 15));

How do I write an arrow function in ES6 recursively?

Arrow functions in ES6 do not have an arguments property and therefore arguments.callee will not work and would anyway not work in strict mode even if just an anonymous function was being used.
Arrow functions cannot be named, so the named functional expression trick can not be used.
So... How does one write a recursive arrow function? That is an arrow function that recursively calls itself based on certain conditions and so on of-course?
Writing a recursive function without naming it is a problem that is as old as computer science itself (even older, actually, since λ-calculus predates computer science), since in λ-calculus all functions are anonymous, and yet you still need recursion.
The solution is to use a fixpoint combinator, usually the Y combinator. This looks something like this:
(y =>
y(
givenFact =>
n =>
n < 2 ? 1 : n * givenFact(n-1)
)(5)
)(le =>
(f =>
f(f)
)(f =>
le(x => (f(f))(x))
)
);
This will compute the factorial of 5 recursively.
Note: the code is heavily based on this: The Y Combinator explained with JavaScript. All credit should go to the original author. I mostly just "harmonized" (is that what you call refactoring old code with new features from ES/Harmony?) it.
It looks like you can assign arrow functions to a variable and use it to call the function recursively.
var complex = (a, b) => {
if (a > b) {
return a;
} else {
complex(a, b);
}
};
Claus Reinke has given an answer to your question in a discussion on the esdiscuss.org website.
In ES6 you have to define what he calls a recursion combinator.
let rec = (f)=> (..args)=> f( (..args)=>rec(f)(..args), ..args )
If you want to call a recursive arrow function, you have to call the recursion combinator with the arrow function as parameter, the first parameter of the arrow function is a recursive function and the rest are the parameters. The name of the recursive function has no importance as it would not be used outside the recursive combinator. You can then call the anonymous arrow function. Here we compute the factorial of 6.
rec( (f,n) => (n>1 ? n*f(n-1) : n) )(6)
If you want to test it in Firefox you need to use the ES5 translation of the recursion combinator:
function rec(f){
return function(){
return f.apply(this,[
function(){
return rec(f).apply(this,arguments);
}
].concat(Array.prototype.slice.call(arguments))
);
}
}
TL;DR:
const rec = f => f((...xs) => rec(f)(...xs));
There are many answers here with variations on a proper Y -- but that's a bit redundant... The thing is that the usual way Y is explained is "what if there is no recursion", so Y itself cannot refer to itself. But since the goal here is a practical combinator, there's no reason to do that. There's this answer that defines rec using itself, but it's complicated and kind of ugly since it adds an argument instead of currying.
The simple recursively-defined Y is
const rec = f => f(rec(f));
but since JS isn't lazy, the above adds the necessary wrapping.
Use a variable to which you assign the function, e.g.
const fac = (n) => n>0 ? n*fac(n-1) : 1;
If you really need it anonymous, use the Y combinator, like this:
const Y = (f) => ((x)=>f((v)=>x(x)(v)))((x)=>f((v)=>x(x)(v)))
… Y((fac)=>(n)=> n>0 ? n*fac(n-1) : 1) …
(ugly, isn't it?)
A general purpose combinator for recursive function definitions of any number of arguments (without using the variable inside itself) would be:
const rec = (le => ((f => f(f))(f => (le((...x) => f(f)(...x))))));
This could be used for example to define factorial:
const factorial = rec( fact => (n => n < 2 ? 1 : n * fact(n - 1)) );
//factorial(5): 120
or string reverse:
const reverse = rec(
rev => (
(w, start) => typeof(start) === "string"
? (!w ? start : rev(w.substring(1), w[0] + start))
: rev(w, '')
)
);
//reverse("olleh"): "hello"
or in-order tree traversal:
const inorder = rec(go => ((node, visit) => !!(node && [go(node.left, visit), visit(node), go(node.right, visit)])));
//inorder({left:{value:3},value:4,right:{value:5}}, function(n) {console.log(n.value)})
// calls console.log(3)
// calls console.log(4)
// calls console.log(5)
// returns true
I found the provided solutions really complicated, and honestly couldn't understand any of them, so i thought out a simpler solution myself (I'm sure it's already known, but here goes my thinking process):
So you're making a factorial function
x => x < 2 ? x : x * (???)
the (???) is where the function is supposed to call itself, but since you can't name it, the obvious solution is to pass it as an argument to itself
f => x => x < 2 ? x : x * f(x-1)
This won't work though. because when we call f(x-1) we're calling this function itself, and we just defined it's arguments as 1) f: the function itself, again and 2) x the value. Well we do have the function itself, f remember? so just pass it first:
f => x => x < 2 ? x : x * f(f)(x-1)
^ the new bit
And that's it. We just made a function that takes itself as the first argument, producing the Factorial function! Just literally pass it to itself:
(f => x => x < 2 ? x : x * f(f)(x-1))(f => x => x < 2 ? x : x * f(f)(x-1))(5)
>120
Instead of writing it twice, you can make another function that passes it's argument to itself:
y => y(y)
and pass your factorial making function to it:
(y => y(y))(f => x => x < 2 ? x : x * f(f)(x-1))(5)
>120
Boom. Here's a little formula:
(y => y(y))(f => x => endCondition(x) ? default(x) : operation(x)(f(f)(nextStep(x))))
For a basic function that adds numbers from 0 to x, endCondition is when you need to stop recurring, so x => x == 0. default is the last value you give once endCondition is met, so x => x. operation is simply the operation you're doing on every recursion, like multiplying in Factorial or adding in Fibonacci: x1 => x2 => x1 + x2. and lastly nextStep is the next value to pass to the function, which is usually the current value minus one: x => x - 1. Apply:
(y => y(y))(f => x => x == 0 ? x : x + f(f)(x - 1))(5)
>15
var rec = () => {rec()};
rec();
Would that be an option?
Since arguments.callee is a bad option due to deprecation/doesnt work in strict mode, and doing something like var func = () => {} is also bad, this a hack like described in this answer is probably your only option:
javascript: recursive anonymous function?
This is a version of this answer, https://stackoverflow.com/a/3903334/689223, with arrow functions.
You can use the U or the Y combinator. Y combinator being the simplest to use.
U combinator, with this you have to keep passing the function:
const U = f => f(f)
U(selfFn => arg => selfFn(selfFn)('to infinity and beyond'))
Y combinator, with this you don't have to keep passing the function:
const Y = gen => U(f => gen((...args) => f(f)(...args)))
Y(selfFn => arg => selfFn('to infinity and beyond'))
You can assign your function to a variable inside an iife
var countdown = f=>(f=a=>{
console.log(a)
if(a>0) f(--a)
})()
countdown(3)
//3
//2
//1
//0
i think the simplest solution is looking at the only thing that you don't have, which is a reference to the function itself. because if you have that then recusion is trivial.
amazingly that is possible through a higher order function.
let generateTheNeededValue = (f, ...args) => f(f, ...args);
this function as the name sugests, it will generate the reference that we'll need. now we only need to apply this to our function
(generateTheNeededValue)(ourFunction, ourFunctionArgs)
but the problem with using this thing is that our function definition needs to expect a very special first argument
let ourFunction = (me, ...ourArgs) => {...}
i like to call this special value as 'me'. and now everytime we need recursion we do like this
me(me, ...argsOnRecursion);
with all of that. we can now create a simple factorial function.
((f, ...args) => f(f, ...args))((me, x) => {
if(x < 2) {
return 1;
} else {
return x * me(me, x - 1);
}
}, 4)
-> 24
i also like to look at the one liner of this
((f, ...args) => f(f, ...args))((me, x) => (x < 2) ? 1 : (x * me(me, x - 1)), 4)
Here is the example of recursive function js es6.
let filterGroups = [
{name: 'Filter Group 1'}
];
const generateGroupName = (nextNumber) => {
let gN = `Filter Group ${nextNumber}`;
let exists = filterGroups.find((g) => g.name === gN);
return exists === undefined ? gN : generateGroupName(++nextNumber); // Important
};
let fg = generateGroupName(filterGroups.length);
filterGroups.push({name: fg});

Categories

Resources