Posts by hkotsubo • 55,826 points
1,422 posts
-
1
votes1
answer33
viewsA: Scroll through a list to get the current element and the next
You don’t have to make a for inside each other. Just make a single loop, only using the indexes. Then you go from the first to the penultimate, and to get the next one, just pick up the following…
-
0
votes1
answer25
viewsA: How to use destructuring assignment to build a new object with common attributes?
Need to use destructuring assignment? I think you need it, you don’t need it... let dados = [ {nome: "Ricardo Graciolli", id: "2", atendimentos: "12", horario: "12:00"}, {nome: "Ana Paula Germano",…
-
3
votes1
answer63
viewsA: Regex Python Remove everything before the first letter in a string
In his example, t is a list, so it’s no use passing it directly to re.sub. You have to pass one string at a time. Therefore, one option is to use: import re t = ['. Subordinam-se ao regime', '1º O…
-
4
votes1
answer39
viewsA: regex python delete all after the second occurrence of a whitespace
Just do: print(re.sub(r' [^ ]+$', '', teste)) regex has a space (note that there is a space after the '), followed by one or more characters that are not space ([^ ]+), and the end of the string…
-
2
votes2
answers62
viewsA: How to use print for special Python characters?
The character \ has special meaning in strings: it is used for escape sequences (for example, \n represents the line break, \t represents the GRT, etc). And in case, \' represents the character…
-
4
votes1
answer65
views -
1
votes3
answers66
viewsA: How to remove values that are in another list?
An alternative is to turn the time lists into set's and subtract them. So what’s left are the available times: schedules_dict = {1: ['00:00'], 2: ['00:30', '00:45'], 3: ['00:00', '00:30', '00:45']}…
-
2
votes1
answer35
viewsA: Splitting always 0 even with variables having values. Bug List/Arraylist
That’s not bug, is a very well defined behaviour in language specification. Basically, if both operands are int, the result of the split will also be int, and the value is rounded. So when dividing…
-
2
votes2
answers57
viewsA: How to get all <ul> elements using Document.querySelectorAll() - Javascript
When you search for .latasDeRefri, is bringing only the element that has the class "latasDeRefri", which in this case is the ul. If you want all the li inside it, just include this in the selector:…
-
5
votes3
answers179
viewsA: Basic Python repetition - doubt in "and" and "or"
The or indicates that if any of the conditions are true, that is enough. For example, if the last digit is 2, the first condition (which tests if it is non-zero) is true and it already enters the…
-
1
votes1
answer53
viewsA: How to modify a variable within a definition without globalizing the variable?
In fact, without using global variable, it is not possible to do what you want. Because if I do: def f(mmm): mmm = 1 return mmm f(10) Note that I called the function by passing a value directly…
-
2
votes2
answers62
viewsA: Find the longest word using . Sort()
If you want to pass the words as parameters to the function (as in your example: findLongestWord("The", "quick", "brown")), then one option is to use Rest Parameters: function…
-
4
votes2
answers261
viewsA: How to validate if one date is longer than the other considering day, month and year
The problem is that format returns a string, and strings are compared lexicographically, ie even digits like 0 and 1 are treated as characters, and therefore a string that starts with 0 is…
-
2
votes1
answer37
viewsA: My algorithm generates a SHA512 Hash displays an unexpected result
The method ComputeHash returns an array of bytes. When using Encoding.UTF8.GetString, you are trying to turn these bytes into a text, using UTF-8 encoding (related reading, if you want to understand…
-
3
votes1
answer45
viewsA: Replace multiple substrings of a dictionary
First let’s modify your example a little to better understand what happens: dicionario = { "uva":"R$ 5,00" } for key, value in dicionario.items(): print('substituindo', value) if 'R$ ' in value or…
-
3
votes1
answer190
viewsA: How to count multiple characters from a string using Python
If the cracks are separated by space, an alternative is to separate them using split and count how many are equal to "ATC": seq = 'ATC CAA GTC AGC TAG CGT ATC ATC GTC ATG CTC AAA CAC TAC GAT GCT…
-
4
votes2
answers704
viewsA: Error: Unsupported operand type(s)
What happens is that input returns a string, and you tried to add these strings to the number that is in soma. Then you must use int to convert the string to number. But there are other details. No…
-
1
votes1
answer49
viewsA: how do I use the for correctly?
Just multiply the denominator by 2. See that there is a pattern: the first term is 1 divided by 2 the second term is 2 divided by 4 the third term is 3 divided by 8 ... That is, with each new term,…
-
2
votes2
answers1193
viewsA: Is there any way to overwrite a specific line of a text file using Python?
Complementing the another answer, which at the end commented on the following: However, in this way, the content ends up being stored in memory through the buffer, which can affect the performance…
-
1
votes1
answer33
viewsA: I’m trying to open a file with Jfilechooser and read with Bufferedreader but is only reading the last line
It is reading the entire file yes. The problem is that you overwrite what has already been read and only use the last line read: String linha = br.readLine(); while (linha!=null){ ta.setText(linha);…
-
2
votes2
answers62
viewsA: Remove numbers and special characters from a text, but not within a word
An alternative is to use lookarounds: resultado = re.sub(r"(?<!\w)([^\w\s]|\d)+(?!\w)", " ", texto) (?<!\w) is a lookbehind negative if earlier nay has a \w, and (?!\w) is a Lookahead negative…
-
3
votes1
answer61
viewsA: Date count of days when it has turn of year
The problem is that strftime returns a string containing the date representation, not the date itself. If you want to compare only the date, without taking into account the time, you can convert…
-
2
votes1
answer60
viewsA: Find content between 2 strings inside a giant string with Regexp
The problem is that after "frame" and the number, has a –. But in your regex you used [\w\s], whereas the \w is shortcut representing an alpha-numeric character (a letter, number or _) and the \s…
-
3
votes2
answers57
viewsA: Regex passes the test site but the code does not work
The builder of RegExp takes a string, and in strings the character \ must be escaped with another \, getting \\. I mean, it should be like this: const regexMoneyFormat =…
-
1
votes2
answers248
viewsA: Checking repeated character in Python list
An alternative is to create a set from the string. As a set does not allow duplicated elements, its size will be smaller if the string has some repeated character: def permitido(s): if not s: # se a…
-
2
votes1
answer337
viewsA: How to fix Time limit exceeded error
Probably what makes your code slow is the creation and concatenation of several strings (not counting the Slices as [:-1], which also generate another string). A more efficient way is to use join…
-
2
votes2
answers109
viewsA: Iterating a string inside the for
Just see the documentation of range. But basically, a range has 3 values: initial value final value footstep Where the initial value is included and the end is not (for example, for a range with…
-
1
votes2
answers28
viewsA: Data Calendar updating alone
In the method ObterVencimento you call the method add, that modifies the Calendar. For example, if you do this: Calendar cal = Calendar.getInstance(); // Calendar com a data atual…
-
2
votes1
answer113
viewsA: How to select/find opening and closing quotes in a string using regex?
Getting the contents in quotes If you have exactly one sentence per line, you don’t need regex. Just use split to separate lines and then see if each line starts and ends with quotes: const texto =…
-
1
votes1
answer72
viewsA: How do greedy, non-greedy quantifiers work?
If you do not know very well what you are doing, I suggest you do not use regex for this, there are better solutions (and throughout the answer we will understand the reasons). But anyway, about the…
-
3
votes2
answers96
viewsA: How does logic test work with two integers in Python?
The & is not a logical test, but an operation done with 2 integers, the result of which is another integer. To be more precise, it is a Binary bitwise Operation. In the case, the & makes the…
-
1
votes1
answer99
viewsA: Java: separate row into columns by character position
Do not use regex. If you want to get specific string positions, use substring. Ex: String linha = "012016010402AAPL34 010APPLE DRN R$…
-
1
votes1
answer110
viewsA: Format difference between two dates
First of all, there are two important concepts you should know to understand how to solve your problem: "schedules" and "durations". To better understand, consider the two sentences below: the movie…
-
0
votes1
answer241
viewsA: Runtime error in python 3.8 - URI
The statement makes it clear that the exam grade is only provided if the student is on the exam. Otherwise, there’ll be nothing to read, so you’ll make a mistake trying to use input. Then move the…
-
3
votes3
answers105
viewsA: Find and change specific Python dictionary
To understand why your code doesn’t work, just make a table test, but anyway, let’s understand what happens. The break'Those you put in interrupt the for more internal (what is iterating through the…
-
3
votes2
answers56
viewsA: Problem with toFixed() Javascript method
If the idea is to leave only 2 decimal places, just make some simple calculations: first you multiply by 100, the result will be 1012.5 then round down, resulting in 1012 finally, divide by 100, the…
javascriptanswered hkotsubo 55,826 -
2
votes2
answers368
viewsA: Count occurrences of a letter in a string that repeats several times to a character limit
In doing string_repetida = s * n_repetidos you are creating a string with 1 trillion characters (that is, if each character occupies 1 byte, you will need 1 terabyte for this string, so it gives…
-
3
votes2
answers50
viewsA: How to avoid Greedy Repetition (.*) to search for string that has defined start, dynamic middle and defined end?
To leave the quantifier no-Greedy (also called Lazy, more information here and here), simply change the regex to ^WebServer:.*?endOfLine - the ? shortly after the * makes it not-Greedy. Only in this…
-
1
votes1
answer54
viewsA: How to handle errors if the user enters an invalid character?
There are several problems there, the first is: if n1.isnumeric == False You’re not calling the method isnumeric. In fact, you’re comparing whether the method itself is false, which it never will…
-
0
votes2
answers56
views -
5
votes3
answers77
viewsA: Is there a bash iterator equivalent to the python enumerate?
You can even do it, I just don’t know if it’s as practical as simply accessing the indexes directly, as indicated by another answer. So let’s take parts. First we start from your array:…
-
7
votes1
answer99
viewsA: What are the differences between String.prototype.match and String.prototype.matchAll methods?
One difference is that match returns an array and matchAll returns an iterator, but there are several other details to consider. When the regex doesn’t have the flag g, match returns an array…
-
5
votes4
answers3540
viewsA: How to count occurrences of a letter in a sentence?
Just to complement the other answers, there are some situations you should take care of, since there are surprises that only the Unicode brings to you :-) Take the test below: function…
-
2
votes3
answers105
viewsA: Doubt about Python list
The other answers already explained the problem of your algorithm, but just to give a few more solution options, an alternative is to use a Counter: from collections import Counter def…
-
3
votes1
answer38
viewsA: How to use for comparing a specific index?
If you only want a specific index instead of the entire list, then access the element directly instead of making one for: def bonAppetit(bill, k, b): if bill[k] >= b: # <-- **AQUI** - não…
-
2
votes2
answers355
viewsA: Float to str conversion without losing two decimal places and changing decimal separator
One option is to use locale.format (up to Python 3.6), or locale.format_string (from Python 3.7 as in this version locale.format became deprecated): import locale locale.setlocale(locale.LC_ALL,…
-
4
votes2
answers83
viewsA: Objects eligible for the AG
I think it’s easier to understand if we rework the drawings, seeing what happens line by line. Line 3: Rabbit one = new Rabbit(); An instance of Rabbit, for which the variable one points. That is to…
-
4
votes2
answers311
viewsA: How to use re.split() to pick only the words of a text, ignoring numbers and punctuation marks
In regex, brackets define a character class (that is, what is inside them is a list of possible characters). So [ ,2020().!] means "a space, or a comma, or the digit 2, or the digit 0, or the digit…
-
9
votes4
answers10562
viewsA: Performatively calculate the divisors of a Python number
Yes, you can optimize quite a lot. If you found a divider, then you actually found - in most cases - two. For example, if the number is 100 and I found the divisor 2, then I also found the divisor…
-
10
votes1
answer215
viewsA: Why use a regular expression "compiled" (re.Compile) in Python?
Every regular expression, whether in Python or any other language, is compiled: the Parsing to know if the syntax is correct, if the expression is valid, to get all of its tokens, etc (the details,…