Posts by hkotsubo • 55,826 points
1,422 posts
-
3
votes2
answers737
viewsA: Restarting a Python script with Input
The other answer suggests using recursion, which is a way of doing without while, but it is not the best way, because if the user stays in the loop several times, recursive calls will accumulate and…
-
1
votes2
answers156
viewsA: How to use preg_match_all in this excerpt?
The first detail is that in PHP as regex must have delimiters (a character indicating the beginning and end of the expression). In your case, you used !, so missed putting another ! in the end. In…
-
1
votes1
answer88
viewsA: preg_match_all does not return all values
This happens because of the parentheses in this section of regex: ([^<\/]{1,}). The parentheses form a catch group, and according to the documentation of preg_match_all, in the array of pouch the…
-
6
votes1
answer822
viewsA: What is the difference between the orelse() and orElseGet() methods of java.util.Optional?
Both return something if the Optional has no value. The difference is in the orElse you provide the value to be returned, and orElseGet you provide a Supplier (an object that returns the value). Ex:…
-
0
votes2
answers958
viewsA: preg_split to separate words, but ignoring some
With preg_split you can use as a criterion the regex you already have (spaces, provided you do not have "from", "do", "da", etc before) and add the first word as another possibility: $string =…
-
2
votes1
answer177
viewsA: How to submit the form only if the field is completed
The event of submit refers to the form (form), not to the input, as set out in documentation: Note that the Submit Event Fires on the <form> element itself, and not on any <button> or…
-
3
votes2
answers172
viewsA: How to verify if Valueerror occurred
There’s nothing you can do if delta == ValueError because ValueError is an exception that is thrown by math.sqrt when you pass a negative value: exception is different from value returned, the…
-
6
votes2
answers609
viewsA: Regex for full sentence in capital letters
One solution would be to eliminate everything that is not a letter, and then test if what is left has only uppercase letters: function isUpperCase(s) { return…
-
4
votes2
answers89
viewsA: Change string characters, except the last 4
One of the problems was putting the condition index >= dados.length - 4. Like index starts at zero if dados has size 10, for example, the condition will be false, since zero is not greater than…
-
4
votes3
answers896
viewsA: How to insert a character in the middle of the sentence
One solution is to scroll through the string characters, and only add the "x" if the next character is equal to the current one: class Test: def __init__(self, frase): self.__frase = frase; def…
-
3
votes1
answer108
viewsA: Ways to check in real time if an object has been changed
You can use a Proxy, that according to the documentation: is used to define custom behavior for fundamental Operations (e.g. Property lookup, assignment, enumeration, Function Invocation, etc) That…
javascriptanswered hkotsubo 55,826 -
2
votes2
answers215
viewsA: How to access the lines of a file read by readlines()?
To another answer already explained very well the problem of using readlines several times, but lacked a small detail: both readlines when readline do not delete line breaks from the file, and the…
-
3
votes2
answers152
viewsA: Can anyone explain to me how this code works?
To another answer already explains how the code works, so I’ll focus on your other question: There’s no simpler way to do that number-for-letter exchange? There are other ways to do it, but whether…
-
2
votes2
answers126
viewsA: Adding elements to a dictionary only if the key does not exist
This happens because of the order in which things are done (and it could be detected by making a table test). First you add the student in the dictionary: alunos[nome]=[notas] Then you check if this…
-
4
votes4
answers1133
viewsA: Add negative elements from a list
One of the reasons the code doesn’t work is the lack of identation after the if: if n < 0: soma_dos_negativos = sum(n) It causes a IndentationError. For the code to be executed only if n is…
-
3
votes2
answers99
viewsA: Javascript . NET Zip() method
A solution would be to create a function that receives an array and the function that is applied to the elements. You can add in prototype of Array to make it available to any array:…
-
2
votes1
answer336
viewsA: Calculate difference between dates (no time) with strtotime - use of date_default_timezone_set() gives different results
Difference between dates is more complicated than it seems. In your case, it seems to be a problem related to daylight saving time. In the Timezone America/Sao_Paulo, in 2019, daylight saving time…
-
3
votes2
answers61
viewsA: Error when assigning native function context
First we have to understand what bind makes. According to documentation: creates a new Function that, when called, has its this keyword set to the provided value That is, the bind creates a new…
javascriptanswered hkotsubo 55,826 -
6
votes1
answer85
viewsA: Object access bracket notation does not accept String object
In its object afraid not all values are functions. The key value 'Monday', for example, it is a number. Only keys Tuesday and Fryday have functions as value. So it is only possible to call these…
-
2
votes1
answer45
viewsA: Get list elements after Insert
The method insert returns None, then all its variables v1, v2, v3 and v4 will have the value None (that is, they will have no defined value). If you want to access the list values individually, you…
-
2
votes3
answers127
viewsA: Code does not work as expected
You didn’t report the data you used to test, but the problem probably occurs because the weight should be a number, but in the code you manipulate it as a string (since input returns a string). The…
-
3
votes2
answers3800
viewsA: Format number with Javascript
Complementing the accepted answer, there is still another alternative, which is to use a Intl.NumberFormat. Its operation is similar to toLocaleString: let formatador = new…
-
4
votes1
answer305
viewsA: Convert String to Date and check if it is a valid Javascript date
The builder of Date does not accept any string in any format. In this case, the string 30062016 in fact it is not accepted. And call Date.parse with the same string does not help, because so much…
-
7
votes2
answers769
viewsA: How to return values with numbers in an array
The indexes of an array start at zero. So if an array has 4 elements, the indexes go from 0 to 3. But in the for you put i <= 4, then it will try to access index 4, which does not exist, so first…
-
1
votes1
answer56
viewsA: How to make a condition with operators "+", "-", "*","/"
In Perl, strings should be compared with the operator eq: if ($op eq "+") { $total = $valor1 + $valor2; print ($total); } elsif ($op eq "-") { $total = $valor1 - $valor2; print ($total); } elsif…
-
1
votes2
answers182
viewsA: Format "hour:minute" duration to ISO 8601 format
The problem with your code is that the bars at the beginning and end are regex delimiters. Therefore, when another bar is found in the middle of the expression, PHP thinks that regex is over and…
-
4
votes2
answers437
viewsA: Regex to find text between square brackets
The brackets have special meaning in regex: they create a character class. For example, [abc] means "the letter a or the letter b or the letter c" (any of them). So the expression [Ticket: (\d+)] is…
-
4
votes5
answers821
viewsA: Avoid blank input data
Contrary to what some responses have stated, you should not remove items from the list within it loop that iterates on it. It may even work in some cases, but in others it won’t, as we can see…
-
2
votes2
answers379
viewsA: How to search for partial text in a string list?
You can use the operator in to check if a string is a substring from another. It’s just not clear if you only want one of the strings in the list (the first one you find, for example), or if you…
-
6
votes3
answers11154
views -
6
votes4
answers1011
viewsA: Replace a string’s letters with their respective alphabet position
You said the string "faebcd" must become "615234". But what if the string is "klm", then she becomes "111213" (After all, "k", "l" and "m" are respectively the 11th, 12th and 13th letters of the…
-
1
votes2
answers255
viewsA: Regular expressions to fix the format of a field as it is typed
From what I understand, you want to go removing the invalid characters as these are typed. For example, if after the "W" you can only have digits, and the user type an "x", the string becomes "Wx",…
-
2
votes2
answers86
viewsA: Formatting multiple float values does not align when the number of digits is different
The problem of using \t is that if the size of the data varies, in fact its formatting may be "crooked". An alternative is to set a size to be occupied by each information, using the specific…
-
3
votes2
answers110
viewsA: Doubt using array
Let’s go in pieces: int[][] array Here is declared an array of arrays of int. It is an array in which each element is another array, which in turn contains integers. int[][] array = new int[3][5];…
-
1
votes1
answer95
viewsA: A single regex for two different options
Just one detail, one of the regex you used: let A1 = /^A3\d{16}.{26}\d{15}$/; Does not match the example text: A220180829Dinheiro 1000000300767 A310180829Dinheiro 2000000002600 'Cause after "A3,"…
-
5
votes2
answers143
viewsA: Random Hoice and shuffle with different behaviors
According to the documentation module random, random.choice returns one of the elements of the list, chosen randomly. In its first code, this return was placed in the variable a (that is, it…
-
5
votes6
answers491
viewsA: Optimize code in Python
You can do it like this: n = input('Digite o texto todo em maiúscula: ') while True: if n.isupper(): print('Texto correto') break else: n = input('Texto errado, digite tudo em maiúscula: ') while…
-
2
votes2
answers2441
viewsA: Convert date and time to numeric value in Javascript
That numerical value (1462280400000) is the timestamp, which is the amount of time that has passed since the Unix Epoch (whereas the Unix Epoch corresponds to 1 January 1970 at midnight, in UTC).…
-
5
votes3
answers4467
viewsA: How to take part of a String up to a specified character?
Well, there is an alternative - in my opinion, kind of "ugly" - and that "serves" specifically for the case of the question (which has numbers at the beginning). I leave it here as a curiosity: let…
javascriptanswered hkotsubo 55,826 -
3
votes2
answers145
viewsA: Recursive method to display the representation of an integer in a base
To convert to base 10, you could do so: def base(n, b): if n == 0 or b == 10: return n return (n % b) + 10 * base(n // b, b) If the number is zero or the basis is 10, there is no account to do, then…
-
2
votes2
answers124
viewsA: Count letter occurrences in a case insensitive sentence
I couldn’t understand what you meant by "when I add the .lower() she changes to str and the code no longer works", but anyway, if you want to capitalize everything (or everything in capital letters)…
-
2
votes2
answers374
viewsA: What are the valid delimiters for preg_regular expressions?
Only by complementing the another answer, if you use the characters {, (, [ or < at the beginning, the final delimiter cannot be the same character: preg_replace('{\D+{', '', $numero); // erro:…
-
0
votes2
answers119
viewsA: Continue searching in the same Regex
regex only looks for patterns in a text, but the expression itself does not substitute. If you want to manipulate the found result, an alternative would be to first fetch the numbers you want (with…
-
1
votes4
answers140
viewsA: Exercise: Quick replacement
A first problem is that you stated function substituicaoRapida ( ), that is, the function does not receive any parameter. And inside it, you always use the same text ("Good afternoon"), so no matter…
-
0
votes1
answer2137
viewsA: Method Matches() to validate if string contains only numbers
The first code doesn’t work because "seq" (in quotes) is a String which contains the text "seq", and has nothing to do with the variable seq. That is to say, "seq".matches("\\d") is checking whether…
-
2
votes2
answers327
viewsA: I’m having trouble picking a value between two strings in PHP using REGEX
The problem with your regex is that you used the point, which in regex means "any character" (except line breaks), together with the quantifier * (meaning "zero or more occurrences"). Only by…
-
3
votes2
answers548
viewsA: How to convert the hash() value of a string back to the original string?
There is no way to get the original string from the hash. To understand the reason, let’s see how the hash works. According to the documentation, hash receives an object (any one, not just strings)…
-
7
votes2
answers420
viewsA: Regular expression that recognizes Portuguese words (accented) using Python
An alternative is to use the shortcut \w, than in Python 3, by default, already picks accented letters: from re import findall def frequency(string): palavras = findall(r"\w+", string) dicionario =…
-
1
votes1
answer58
viewsA: Regular expression: how to apply "Negative Lookahead" to only one capture group?
Just put the Lookahead within group 2, and modify it a little: the link you saw uses the markers ^ and $, which indicate the start and end of the string, so they check the entire string. If you do…
-
17
votes1
answer1853
viewsA: What does the number returned by System.currentTimeMillis represent?
The method System.currentTimeMillis returns the value of timestamp in milliseconds (also known as "thousandths of a second"). But let’s go in parts. As you saw in the documentation, the return is…