Posts by hkotsubo • 55,826 points
1,422 posts
-
4
votes2
answers277
viewsA: How to capture a number in a string using regular expressions (or similar method) in Python?
If the idea is to take only the numbers that are between # and %, then do: import re texto = "# 44,739 % of all cache refs 12,345 lorem ipsum # 98,736 % etc 45,678 blablbla" r =…
-
1
votes1
answer46
viewsA: How to know if a variable has already been defined in Bash?
One way to do it is: export API_BASE_URL=${API_BASE_URL:="http://localhost"} If the variable already exists, use the current value. Otherwise, use http://localhost. Only that the value is also set…
-
1
votes3
answers131
viewsA: Subtract 1 month from a date string in the dd/mm/yyyy format
Just to complement the other answers, it’s worth explaining why it’s better to use a date API instead of manipulating the string directly. First because, in addition to giving more work, string…
-
4
votes1
answer167
viewsA: Shell Script to calculate average runtime
From what I read around (here, here, here, etc), bash arithmetic is limited to integers. For floating point numbers, it is necessary to use other commands or utilities. One option is to use bc:…
-
3
votes3
answers164
viewsA: Read more than one line with input
According to the documentation, input reads a line and returns it as a string ("reads a line from input"). And as you said you’re pasting all the numbers at once (and they’re one in each row), the…
-
4
votes1
answer58
viewsA: Problems tried to change function next()
The first mistake is here: n = NextPrime Are you saying that n will receive its own class NextPrime, and not an instance of it. To instantiate the class you should use parentheses: n = NextPrime()…
-
3
votes1
answer79
viewsA: Wrong timezone in JAVA
According to the documentation, the lowercase letter "h" corresponds to "hour in am/pm", with values between 1 and 12 (i.e., it is an ambiguous field, which makes more sense if you also use the…
-
3
votes1
answer544
viewsA: Typeerror: 'int' Object is not iterable
The problem, as they say, is that you’re using extend, which receives an iterable and adds all the elements of this in the list. But you are passing a number, which is not iterable. Then you should…
-
4
votes2
answers54
viewsA: how to take duplicates from a list of dictionaries
One way to solve it is to make the country’s name itself the key to the dictionary. And the value of this can be another dictionary containing the amount of medals. Thus, it is possible to get the…
-
4
votes2
answers456
viewsA: Draw triangle with repetition structure in Python
An alternative is to make a loop from 1 to n, increasing the number (adding the new digit at the end) and printing using the formatting options: def triangulo(n): x = 0 for i in range(1, n + 1): x =…
-
2
votes2
answers315
viewsA: Given a number, get the digit of tens
With 321, the result is 32 because you only divide the number by 10 - and the operator // makes the "entire division", that is, round the result. And 321 divided by 10 gives 32. What’s left is to…
-
5
votes1
answer124
viewsA: Why is the "in" method for checking if an element belongs to a collection so slow?
First of all, if you want to test run time, a quick and a little more reliable way is to use the module timeit. That said, the search using the module bisect is faster because she makes a binary…
-
5
votes2
answers131
viewsA: Break string into array limiting the amount of times the break is made
One solution is to do the split and then join the parties together according to what you want: const vogais = "a-e-i-o-u"; const arr = vogais.split('-'); const arrayVogal = [arr[0],…
-
2
votes2
answers126
viewsA: How to create nested and counting dictionaries from lists/tuples?
No need to complicate creating 2 dictionaries (one with the names and the other with the counts). Do it all at once: navio_fatiado = [ [('Ferrari', 'CONV'), ('Audi', 'SEDAN')], [('Fusca', 'CONV'),…
-
2
votes1
answer44
viewsA: How can I check if an element of a list that corresponds to the value of a dictionary is related to the key?
First, the reading of the 5 entries should not be done inside the while, because you already know it will be 5 lines. The while it is only after, to read the cases in which you will verify whether…
-
2
votes2
answers161
viewsA: Recursiveness in Java
I think it gets easier if each CentroCusto have a list of children: public class CentroCusto { private Long id; private CentroCusto pai; private List<CentroCusto> filhos; // lista dos filhos…
-
3
votes1
answer30
viewsA: Sum quantities in objects with identical properties
You really need to use reduce? A loop simple solves: let arr = [ {id: "xxx", amount: 2}, {id: "xxx", amount: 7}, {id: "yyy", amount: 2}, {id: "yyy", amount: 5}, {id: "zzz", amount: 5} ]; let result…
-
1
votes2
answers82
viewsA: Print letters that are outside of Collections. Counter
According to the documentation, one Counter is a subclass of dict, and so it’s also a dictionary. So it’s possible to check if an element exists and get it, just like we do with dictionaries. To get…
-
1
votes2
answers49
viewsA: Len and Max Float together Python
If you have any list (not necessarily typed by the user), you can use the another answer. But in your specific case, where the user is typing the data, you can already calculate everything in the…
-
0
votes1
answer54
viewsA: I’m not able to do the listing to know how many products were sold and the quantity
The problem is here in the function call vendas: vendas(produtos) You are passing the list produtos as a parameter. But how produtos has tuples with 3 elements, and in the function you only try to…
-
2
votes1
answer28
viewsA: How do I egrep print the matchlist of a file?
According to the documentation, just use the option -o or --only-matching: egrep -o '\bS[a-z]+' bezos.txt egrep --only-matching '\bS[a-z]+' bezos.txt This option is described as: -the,…
-
2
votes2
answers68
viewsA: Regex extract substring from text delimited by an end pattern that repeats in the text (Starttextofim Starttextofim)
First, an explanation about [\S\s]: this is a "trick" known to pick up "any character". Usually we use the dot for "any character", but by default, the point does not consider line breaks, then…
-
4
votes3
answers280
viewsA: Finish a loop when a given string is typed
Instead of calling input twice (one out of the while and another inside), do it once: lista = [] while True: i = input('Digite um número (ou "." para encerrar): ') if i == '.': break # sai do while…
-
5
votes4
answers2518
viewsA: How to count occurrences of a value within an array?
Just to complement the another answer: use filter actually works, but you have to remember that filter returns another array with the filtration results. If you want to know only the amount of…
-
2
votes1
answer95
viewsA: How to browse a dictionary within a python list?
It gets easier if you understand the structure of a JSON (and it’s not that hard): You have an object (because it is bounded by { }), which has a single key called "Airports". The value of this key…
-
2
votes4
answers412
viewsA: How to check if a list contains 3 consecutive numbers
Well, for each element, you need to check the next 2 (i.e., for each position i, you need to check the positions i + 1 and i + 2). Then you must iterate up len - 2 instead of len - 1: numeros = [10,…
-
3
votes1
answer79
viewsA: querySelector e querySelectorAll
As stated above here, querySelectorAll returns a list of elements, then you should scroll through this list to add the events in each element. Now querySelector returns only the first element found.…
-
0
votes1
answer141
viewsA: How to create a variable-sized array in Java?
No, arrays have a fixed size. If you want a flexible structure, without having to specify the size, and that grows as needed, you should use ArrayList. int[] numeros = new int[10]; for (int i = 0; i…
-
6
votes2
answers262
viewsA: Sort string in ascending order according to numeric value
When you do the split, the result is an array of strings. Only that strings are compared lexicographically, that is, it takes into account their characters to define which is "larger" or "smaller".…
javascriptanswered hkotsubo 55,826 -
1
votes1
answer56
viewsA: Problem to add data to a dictionary
This here nay is a dictionary: Notas = {'Total:', 'Maior:', 'Menor:', 'Média:', 'Situação:'} In fact you created a set. What can confuse is that to create set's and dictionaries, keys are used as…
-
1
votes1
answer60
viewsA: Return multiple keys using REGEXP_SUBSTR
It wasn’t very pretty, but anyway. If you’re using Oracle >= 11g, you can use the sixth parameter of REGEXP_SUBSTR. Assuming the value in question is in the campo of a tabela: select SUBSTR(s, 1,…
-
1
votes1
answer94
viewsA: Studying lists
First of all, don’t call the function within itself, as you did with opc(). Although "working", it is not ideal. This is because each time a function is called, it is "stacked" (placed on the…
-
2
votes1
answer92
viewsA: Regular Expression for numbers between certain ranges
Simple, all the characters you put between brackets are actually a character class: a list of characters that must be accepted. For example, [abc] means "the letter a, or b, or c" (any of them). And…
-
1
votes1
answer54
viewsA: Get the lowest value with the map in a Dict
The function item is modifying the price value because you do p['preco'] = valor, then it doesn’t seem to be what you need. Moreover, map serves to apply a function to all elements of an iterable,…
-
1
votes2
answers175
viewsA: Return of prime numbers?
If search here on the site, will find various algorithms to check if a number is prime. Your algorithm only checks if the number is divisible by some prime numbers, up to 23. That’s well limited, as…
-
1
votes2
answers63
viewsA: How to get only a chunk of a command output
Whereas the exit from the control git --version is something like git version 1.2.3, then at the bottom is a matter of getting the final stretch. There are several ways to do this. One is using the…
-
4
votes5
answers1499
viewsA: What is a gluttonous regular expression?
The other answers have already explained what it is, but I think it’s worth explaining as regex internally treats greedy and non-greedy quantifiers, even to clarify what was said in one of the…
-
1
votes1
answer403
viewsA: How to remove the last URL bar
One option is to use rtrim: $url1 = 'http://www.site.com.br/domain1/domanin2/nome/'; $sem_barra = rtrim($url1, '/'); echo $sem_barra; // http://www.site.com.br/domain1/domanin2/nome The second…
-
3
votes2
answers53
viewsA: How can I exchange elements of a string using the values of an object as argument?
One option is to use replace, passing as the second parameter a function of callback: const operators = { plus: '+', minus: '-', multiplied: '*', divided: '/' }; let question = 'What is 4 plus 6?…
-
4
votes1
answer133
viewsA: What is the use of "." (dot) in PHP’s ltrim, rtrim and Trim functions?
Actually the second parameter contains the list of characters that will be removed, and nay is interpreted as a substring. Example: echo ltrim('abcaabdef', 'cba'); // def In the above example, I am…
-
0
votes1
answer34
viewsA: How do I read a particular java file position, and get the values from it?
When you use split, have to specify the string that will be used to split. How you used " -> ;", he will try to find exactly this stretch (space, hyphen, >, spaces and semicolons). But this…
-
2
votes1
answer131
viewsA: How to use Regex to represent a more complex BNF?
In accordance with informed in the comments, regex is not the ideal tool for this (there are suggested more suitable options), and on this subject I also suggest you read here and here. That said,…
-
8
votes2
answers573
viewsA: Global variable returns Undefined when using this in Node.js
Let’s go in pieces... this within the function According to the documentation, in Node, the this within the function is equal to the global object: function foo() { console.log(this === global); //…
-
1
votes1
answer78
viewsA: format a python list
melhores is a list that can have multiple students, so how should it be formatted? One per line, all on the same line? All in the same row I think is not a good option, because if you have several,…
-
1
votes1
answer47
viewsA: The function returns None although the variable saves the correct result
Missed you return recursive call result: def encontra_impares(lista, indice=0,I=[]): if indice > len(lista) - 1: return I else: if lista[indice] % 2 != 0: I.append(lista[indice]) indice += 1…
-
2
votes2
answers58
viewsA: problems with the Return function
return closes the execution of the. That is, if the code gets there in the return, it exits the function and does not perform anything else that is within the function. If you want to repeat…
-
4
votes5
answers1031
viewsA: Check that all items in the list are equal
The problem is that when i arrives at the last element, i + 1 tries to access an element that does not exist. Then you should only go to the penultimate element. Another point is that you don’t need…
-
1
votes3
answers126
viewsA: String to date.parse Javascript conversion problem
According to the documentation, the only format that is guaranteed to work the same way in all browsers (described here) is based on the standard ISO 8601 (in his example, it would be "2020-12-31").…
-
4
votes1
answer202
viewsA: How to use the negation operator in regular expressions for a specific string?
[^\.\s] is a character class denied which means "a character that nay is neither point nor space". What is between [^ and ] is a list of characters, and there is no order defined between them - so…
-
3
votes1
answer100
viewsA: Recursive Binary Search does not find the element at the last vector position
In a binary search, one of the prerequisites is that all elements are in order, otherwise nay there is no guarantee that will work. In your case, the array is not ordered, because the penultimate…