Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'am newbie in Python and i'am having a hard time trying to translate this Javascript arrow function into Python. I'am not able to make the part where i use substring in JS to get the next 3 values in my loop when i find '\x1D'. Any tips or suggestions ?
module.exports = edi => {
let decompressedEdi = ''
let lastCompressor = 0
for (let i = 0; i <= edi.length; i++) {
if (edi[i] === '\x1D') {
let decimal = parseInt(edi.substring(i + 1, i + 3), 16)
let repeater = edi[i + 3]
decompressedEdi +=
edi.substring(lastCompressor, i) + repeater.repeat(decimal)
lastCompressor = i + 4
}
}
decompressedEdi += edi.substring(lastCompressor, edi.length)
return decompressedEdi.replace(/(\r\n|\n|\r)/gm, '')
}
In python, strings can be sliced like arrays :
for i, c in enumerate(edi):
if c == '\x1D':
decimal = int(edi[i+1:i+3], 16)
The int function has the following signature: int(str, base)
from re import sub
def decompress(edi):
decompressed = ""
last_compressor = 0
for i, c in enumerate(edi):
if c == "\x1D":
repetitions = int(edi[i + 1: i + 3], 16)
repeating_char = edi[i + 3]
decompressed += edi[last_compressor:i] + repeating_char * repetitions
last_compressor = i + 4
decompressed += edi[last_compressor:-1]
return sub("\r\n|\n|\r", decompressed)
How I read the code
Feel free to ignore this bit, but it might help.
Given edi which has a len, for each edi that matches \x1D, get the substring of edi from the index + 1 to index + 3 as a hexadecimal integer as set as decimal. The repeater is the index + 3'th element of edi for each element and it is expected to be a str. It will be repeated the hexadecimal number of times defined in decimal, but only after the substring of edi from lastCompressor to the current index. On each iteration where \x1D is matched, the lastCompressor is increased by 4.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
The example string(s) can look like that:
"3.0000+3"
"3.00+3.00"
"3.00+3.000"
I want to find the highest amount of decimal places out of the numbers inside 1 string
The most straight-forward way to do this is iterating over the string, checking for the occurence of a dot and from there on count the number of digits up to the next character that's NOT a number or the end of the string. Since your string contains multiple numbers you need to add a variable which holds the highest amount of decimal places.
e.g.
var str = "3.00+3.000";
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
console.log(str + " has " + getDecimalPlaces(str) + " decimal places");
This can be made a bit more elegant by using a regular expression in conjunction with the .match() method. This searches a string for a given pattern and returns an array of results.
var str = "3.00+3.000";
console.log(str.match(/(\.)([0-9]+)/g));
This will return an array like:
[".00", ".000"]
By comparing the length of it's elements - minus 1 since it includes the dot - we can get the number of decimal places using this nifty short function:
var str = "3.00+3.000";
var highest = str.match(/(\.)([0-9]+)/g).reduce(function(a, b) {
return Math.max(a.length - 1, b.length - 1);
});
console.log(str + " has " + highest + " decimal places");
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 4 years ago.
Improve this question
I'm trying to add spaces to my input value while the user typing, it works for the constant digits like after 4 letters or after 5 letters. But I couldn't manage to add space after certain digits dynamically.
for example
if user types 1234567890
blocks: [3,3,4]
expected output: 123 456 7890
if user types 1234567890
blocks: [3,2,2,3]
expected output is: 123 45 67 890
Handling inputs as the user types can be tricky.
Although not perfect, one solution is to calculate what the expected result should be, and then compare with what it currently is. If they are different then update the actual input with the calculated one.
Below is a simple example,.. It will even handle were the user pastes in the numbers.
One issue with the below is the cursor position if say you inserted the number mid way, but this could be maybe handled with remembering the cursor position and restoring.
const splits = [3,3,4];
$('#a').on("input", function(){
let count = 0;
const breaks = splits.map(m => { const ret = m + count; count += m; return ret; });
const a = this.value.split("").filter(f => f !== ' ');
const s = a.map((m, ix) => {
if (breaks.includes(ix + 1)) return m + " "
else return m;
}).join("");
if (this.value.trim() !== s.trim()) this.value = s;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="a"/>
Try the below code
function splitValue(value, index) {
return value.substring(0, index) + " " + value.substring(index);
}
var test=[3,3,4];
var secondVar = '';
var firstVar = '1234567890';
for(let i = 0; i < test.length; i++){
var TestVar = splitValue(firstVar, test[i]);
secondVar = secondVar + " " + TestVar.split(" ")[0];
secondVar=secondVar.trim();
if(i == 0)
firstVar = firstVar.replace(secondVar.trim(),'');
else
firstVar = firstVar.replace(secondVar.split(' ')[i + 1],'');
}
console.log(secondVar);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm having a php json_encode object fetched by ajax. whet I want to do is to sum this array. Here's what I did so far:
var json = $.parseJSON(data);
var tot = new Array();
for (var i = 0; i < json.length; ++i) {
tot.push(json[i].final_total);
$('table tbody').append("<tr><td>" + json[i].order_id + "</td><td>" + json[i].final_total + "</td></tr>");
}
Now I want to sum this array. I tried this:
var sum = tot.reduce(function(pv, cv) { return pv + cv; }, 0);
$("#total").html( sum );
But the result is:
09.748.529.129.129.119.59.79.89.79.89.79.79.79.79.79.79719.248.59.79 ......
I also tried:
myFunction(tot);
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("total").innerHTML = item.reduce(getSum);
}
But I got the same result above (Numbers written next to each other).
I also tried this:
var tot = 0;
for (var i = 0; i < json.length; ++i) {
tot += json[i].final_total);
$('table tbody').append("<tr><td>" + json[i].order_id + "</td><td>" + json[i].final_total + "</td></tr>");
}
$("#total").html( tot );
But I got the same result above (Numbers written next to each other).
So what is the proper way to sum an array in javascript?
You have to use parseInt (if the numbers are Integers), parseFloat (if they are Floats) or Number (if not sure) to explicitly interpret them as numbers like:
sum = tot.reduce((a, n) => (a + Number(n)), 0);
Array elements are strings, in order to properly add them, they have to be casted to integer:
var sum = tot.reduce(function(a, b) {
return parseFloat(a) + parseFloat(b);
}, 0);
Taken from MDN:
the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
The is a common issue caused by + operator used for both string concatenation and addition. Issue is best described with following example:
var result = '1' + 3 + 3 + 7 //result is '1337'
Edit: #Pointy - Nice catch, thanks! :)
you will need to use a parse int because its concatenating the sting instead of adding integers
var sum = tot.reduce(function(pv, cv) { return parseInt(pv) + parseInt(cv); }, 0);
parseInt
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
So here is the scenario, I have two values:
var a=1
var b=23
I want a value like (a.b) 1.23:
var a=10
var b=45
I want a value like (a.b) 10.45
Is it possible? Then how?
var a=10; var b=45;
var result = +(a + '.' + b);
+ operator is unary operator for converting a string into a number.
See Mozilla Developer Network.
var a = 10;
var b = 45;
var res = a + (b/100);
Combine them into a string, and then run the result through parseFloat:
var a=1
var b=23
var result = parseFloat(a + "." + b);
Edit: As per #Vostrugin's comment, you can ensure the number of decimal places using toFixed()
parseFloat('0.0').toFixed(2) // this will give you 0.00
var a = 1;
var b = 2;
var c = a + "." + b;
alert(c);
The easiest way to do this is through string concatenation.
It would look like +(a + "." + b)
In JavaScript, a string added to a number becomes a string. A number appended to a string, and the string remains.
However, then we need to convert it to a number. We do that by either using parseInt, or +
Here is an example you can try for yourself
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
var result = document.getElementById("result");
function convertNumber() {
result.innerHTML = (+(n1.value + "." + n2.value));
}
#number-converter {
margin-top: 10px;
}
Number 1: <input type="text" id="n1" />
Number 2: <input type="text" id="n2" />
<button id="number-converter" onclick="convertNumber()">Calculate Number</button>
<p id="result"></p>
var test=function(a,b){
return parseFloat(a + "." + (b>10||b===0?b:(b+"5"))).toFixed(2);
};
console.log(test(1,23));
console.log(test(10,4));
console.log(test(0,0));
//That will always work
//THATS IF YOU WANT THE 10.45 ROUND EFFECT THAT YOU QUEST
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How can I find an extra character between two strings in an optimal way.
Ex1: S1 - 'abcd', S2 - 'abcxd', output - 'x'
Ex2: S1 - '100001', S2 - '1000011', output - '1'
We can do this by traversing linearly and comparing each character in O(n). I want this to be done in much more optimal way, say in O(logn)
Baseline method (O(n)): Just comparing chars and narrowing in on both sides each cycle.
function findDiffChar(base, baseExtraChar) {
let extraLastIndex = base.length;
let lastIndex = extraLastIndex - 1;
for (let i = 0; i < extraLastIndex / 2; i++) {
console.log(`Loop: ${i}`);
if (base[i] !== baseExtraChar[i])
return baseExtraChar[i];
if (base[lastIndex - i] !== baseExtraChar[extraLastIndex - i])
return baseExtraChar[extraLastIndex - i];
}
return false;
}
console.log(findDiffChar('FOOOOOAR', 'FOOOOOBAR')); // B
Improved method using binary search (O(log n)): Compare halves until you've narrowed it down to one character.
function findDiffChar(base, baseExtraChar) {
if (baseExtraChar.length === 1) return baseExtraChar.charAt(0);
let halfBaseLen = Number.parseInt(base.length / 2) || 1;
let halfBase = base.substring(0,halfBaseLen);
let halfBaseExtra = baseExtraChar.substring(0,halfBaseLen);
return (halfBase !== halfBaseExtra)
? findDiffChar(halfBase, halfBaseExtra)
: findDiffChar(base.substring(halfBaseLen),baseExtraChar.substring(halfBaseLen));
}
console.log(findDiffChar('FOOOOAR', 'FOOOOBAR')); // B
console.log(findDiffChar('---------', '--------X')); // X
console.log(findDiffChar('-----------', '-----X-----')); // X
console.log(findDiffChar('------------', '---X--------')); // X
console.log(findDiffChar('----------', '-X--------')); // X
console.log(findDiffChar('----------', 'X---------')); // X