Posts by Gabriel • 1,909 points
91 posts
-
0
votes1
answer85
viewsA: Replace string_concat() with equivalent
According to the deprecation topic of string_concat in Django’s Issue tracker, all occurrences of string_concat may be replaced by format_lazy('{}'*len(params), *params). Example of polyfill, if you…
-
1
votes1
answer123
viewsA: How to perform semantic analysis using pure functional programming without side Effect?
Surely there is a way to do this without side effects. The idea is to use a stateless data structure to represent context. The function that evaluates the AST takes the previous context and returns…
-
0
votes3
answers230
viewsA: Bi-directional asynchronous communication in layers
Use a queue system, like Rabbitmq, or Kafka, or any of your own. Business Layer will publish in the queue all the information necessary to send the emails. Each message in the queue is an email that…
-
0
votes2
answers183
viewsA: Print which (ais) words repeat in Python
It is advisable to use the instruction with to upload files Lists have the method count who does exactly what you need The code would look like this: import re with open('arquivo.txt',…
-
0
votes1
answer51
viewsA: Python bar graph
Use the function xticks to rotate x-axis texts, passing the degree of inclination as a parameter rotation. Example rotating 45°: import matplotlib.pyplot as plt plt.bar(['teste 1', 'teste 2', 'teste…
-
1
votes1
answer69
views -
0
votes1
answer144
viewsA: Ask the user to enter 10 names and then show them reversed in Javascript
No need to write the Divs one by one, just take advantage of the loop for Usually the variable i is stated in the tie itself (only a good practice) Use the function join to concatenate the elements…
-
0
votes1
answer1653
viewsA: doubts of logic in Python
First thing that pops out the eyes is the amount of magic numbers. I’ve turned everything into constants (which are actually not constants, they’re just variables with high-box names). This…
-
4
votes4
answers2518
viewsA: How to count occurrences of a value within an array?
Use the function filter to generate a new array with all the elements you want, and then call the property length of this new array. var teste = [ "oi","tudo","bem","oi"]; var quantidadeElementos =…
-
0
votes1
answer323
viewsA: Calculate the average of a variable for each type of flower in a column
Group the dataset by the flower species, select the column width of the sepals and apply the average function in each group. df_medias = df.groupby(['species'], as_index=False)['sepal_width'].mean()…
-
1
votes3
answers60
viewsA: Shorten Object Method Call
A less repetitive way of verifying that classes have exactly inherited these methods is to use the function hasattr on each object. acoes = ['imprime', 'aposentar', 'aquecer', 'correr', 'nadar',…
-
0
votes1
answer56
viewsA: Why doesn’t he run my read() since I opened it for reading and writing at the same time
You must use the method seek to move the cursor to the first position before running the read. filename = input('Informe o nome do arquivo: ') filename += '.txt' arquivo = open(filename,'w+')…
-
5
votes3
answers179
viewsA: Two different parameters that an accepted function can classify as having O(n²) complexity?
First algorithm It can be classified as having complexity O(n²), right? The first thing you should do is tell your n refers. Is the number of rows in the matrix? The number of columns? The total…
-
3
votes1
answer71
viewsA: What does Typevar’s covariant and contravariant of the Typing module mean?
Imagine that we are programming a game. Our game features several three-dimensional objects, including cardboard boxes. A way to represent that in code would be like this: class Figura3D(): pass…
-
0
votes1
answer217
viewsA: Calculating numerical integrals from numpy arrays
You can simply encapsulate your code in a separate function that receives the list of limits per parameter: def calcular_integrais_triplas(f, limites): resultados = [] for limite in limites: (r, _)…
-
2
votes2
answers87
viewsA: Problem involving classes, vectors and tuples
Syntax You clearly did not execute your own code. If you had executed it, you would have seen that you forgot to use self when accessing class attributes. The code generates an error when calling…
-
2
votes1
answer185
viewsA: Code review: field validations, how to abstract correctly?
Nomenclature You use names in English (textFieldTempoDeEntregaMin) and in English (isSmallerThan). It’s not a big deal, but it makes the project ugly. When I maintain a project that mixes styles of…
-
5
votes4
answers1053
viewsA: Python Queue Code - How to check if there is an element with a specific name in the queue and its index position?
Formatting Your code doesn’t fit the style suggested by PEP 8. Python programmers often use PEP 8 as a guide to formatting code. I strongly recommend that you refactor your code to meet these…
-
0
votes1
answer139
viewsA: Binaria Search - complexity
As we know, the normal binary search algorithm works between two indexes, which are initially the first and last indexes of the array. As you are working with an infinite array, there is no "last…
-
0
votes1
answer42
viewsA: Bubble Sort in python - Problem inserting values in list
To insert items in a list, use the method .append. lista = [] for i in range(0, 4): numero = int(input('Informe um numero: ')) lista.append(numero) See the language documentation:…
python-3.xanswered Gabriel 1,909 -
3
votes1
answer153
viewsA: Non-blocking execution with asynchronous Python functions
To run two tasks concurrently, use the function async.gather. Example: import asyncio async def funcao1(): print('entrando no sono...') await asyncio.sleep(3) print('saindo do sono...') async def…
-
1
votes1
answer48
viewsA: doubt text files in python
I am trying to make a program that reads the file in filename and returns the information concerning the country indicated in parents Generally use underlines to name variables in Python. I…
-
2
votes1
answer244
viewsA: Code Review: Program that simulates the "door game": either you win a car or a goat!
Formatting The spacing of your code is not good. The code is too compact and this hinders reading. Also, there is no standard. Example: testes = int(input("Digite o número de testes: ")) bode =0 On…
-
1
votes2
answers594
viewsA: How to remove all text within a parenthesis?
You want to generate a new text that contains all the characters in the original text, except those surrounded by parentheses. In other words, you want to measure the depth of each excerpt of the…
-
5
votes1
answer427
viewsA: Python - Run the next command without waiting for the end of the first
Note 1: I’ll assume your terminal supports ANSI. Note 2: For simplicity’s sake, I’m not going to go into threads in that answer. The function print Python (and most programming languages) receives a…
-
0
votes1
answer1406
viewsA: Compare two chained lists and return whether they are equal or different
Some comments on your code The formatting is not cool. Search the internet for good code organization and indentation practices, and see if your editor has a command to automatically format. The…
-
1
votes2
answers720
viewsA: Add elements of the first matrix to those of the second matrix in Python
First, create two auxiliary constants to know how many rows and how many columns the matrices will have. (This step is not necessary, but makes the code easier to understand) LINHAS = 5 COLUNAS = 3…
-
0
votes1
answer21
viewsA: Retrieve arguments from a javascript array
You create an object with the data, insert it into an array of 1 element and pass this array to the functions. That is, the array is totally unnecessary. Directly pass the object with the data. let…
javascriptanswered Gabriel 1,909 -
5
votes2
answers377
viewsA: Multiply elements of the first matrix by 3 and decrease elements of the second matrix by 3 in Python
First of all, you don’t have to declare i and j previously to use on that for. Second, you need to convert the elements of mt1 and mt2 for int, because when you do the split it generates a list of…
-
0
votes2
answers129
viewsA: Read an integer greater than 0 and return the sum between the numbers that compose it in Python
I know it’s not the most readable answer, and I don’t recommend using it in production, but out of curiosity I’ll leave a one-Liner that does what was requested by the PO. print('Soma dos dígitos:',…
-
3
votes3
answers82
viewsA: How to display matrix input values without [' ']
There are several ways to do this, as can be seen in the other answers. I will leave a solution that, in my view, is quite elegant. You may have noticed that the function print can receive several…
-
0
votes2
answers1757
viewsA: Request whole numbers and count even and odd numbers
You were on the right track. Let’s start by creating two variables to count how many even and odd numbers are reported. contador_pares = 0 contador_impares = 0 Then we loop asking for the numbers…
-
5
votes3
answers176
viewsA: Doubt exercise with lists
First, let’s create a function called main, which will be the entry point of your program, and put a if ensuring that the function will only be called when the script runs directly. def main(): pass…
-
0
votes2
answers63
viewsA: How to Catch the Smallest Value of a Series of Inputs
Start the variable barato with None barato = None And in all the lines where you check if the value is the cheapest, change the elif for if and add the test barato is None or ... I mean, where was…
-
0
votes2
answers750
viewsA: Convert a byte variable into a string?
The method .decode works with variables as well, not only with literals. Run the following code and see: original = 'Olá, mundo' encodado = original.encode('utf-8') decodado =…
-
0
votes1
answer62
viewsA: What is the best way to manipulate schedules using python 3?
The module datetime, which comes by default in Python, is one of the best I’ve ever used for date, time and time intervals manipulation.…
python-3.xanswered Gabriel 1,909 -
3
votes4
answers388
viewsA: How can I add a hyphen between all even numbers of a value?
You can use a purely regex approach. The "cat jump" is Use Lookahead to not lose overlay patterns. Use backreference to reinsert found digits Example: import re resultado =…
-
1
votes1
answer186
viewsA: Python Machine Learning to Predict Multiple Choice Quiz Template
Without knowing what the PRNG used by the bank to generate evidence, it will be very difficult to make this kind of forecast. In short, by discovering the PRNG used and its respective seed, you can…
-
0
votes2
answers250
viewsA: Join two matrices and display them in a third vertically
The two matrices received in the input form a 2x7 matrix, and the result you want to get is a transposition 2x7 matrix. This is simple to do in Python. m1 = input().split() m2 = input().split() m3 =…
-
2
votes1
answer80
viewsA: Populate vector and check if current position value is equal to previous
i want Randomize random numbers without repeating any value in the vector First, let’s create a function that returns a random number within a specific range. function obterNumeroAleatorio(minimo,…
-
3
votes2
answers1074
viewsA: Inner Join no entityframework
The RU has a method called Join. Look at the Docs Your code would look something like this: ObjectSet<Produto> produtos = db.Produto; ObjectSet<SProdutosEmpresas> produtosEmpresas =…
-
0
votes3
answers139
viewsA: Lists within lists: Even when sliced, there is connection between lists
changed in list b, also changed in list a You nay changed the list b. What you’ve changed is a list that is within of b. This internal list is shared between a and b, because the operation of Slice…
-
0
votes3
answers872
viewsA: How to validate if a value is a tuple having a string and an integer?
Use the function isinstance passing each element and type. It follows a function that generalizes this idea: def verificar_tipos(tupla, tipos): return all(isinstance(elemento, tipo) for elemento,…
-
0
votes1
answer51
viewsA: Problem Related to graphs
The text of the problem explains that friends will be selected according to the level away from Rerisson. In other words, there has to be at most n edges between Rerisson and the selected persons. A…
-
-1
votes1
answer286
viewsA: Is it possible to compile C/C++ from Windows/Linux for Macos?
Yes, it is possible. In fact, C++ compilers alone always generate cross-platform code. What makes the code incompatible is when the programmer uses some library or command that is not available on…
-
0
votes2
answers325
viewsA: Doubt in Complexity of Algorithms
There’s absolutely nothing wrong. If f ∈ O(g) and g ∈ O(h), then f ∈ O(h). That is, every function f(n) belongs to O(g(n)) if for all n it is true that g(n) >= f(n). It is clear that for all n it…
answered Gabriel 1,909 -
1
votes1
answer718
viewsA: Implementation of a Lexical Analyzer
Your language is too complex to define in a regular grammar. You should use a context-free grammar, this way you can even define the origin of the mathematical operators and check balanced…
-
1
votes1
answer707
viewsA: How to calculate the complexity of this algorithm?
This algorithm is O(i * n^2) considering the worst case (a complete graph), where: n is the amount of nodes in the graph ì is the value of the variable iteration This happens because the greatest…
answered Gabriel 1,909 -
0
votes1
answer87
viewsA: What is the difference between the complexity of an algorithm and the complexity of a problem?
The correct terminology is to say that a problem belonging to a class time-consuming. To know which class a problem belongs to, we must see which is the best algorithm that solves that problem…
computer-theoryanswered Gabriel 1,909 -
1
votes1
answer474
viewsA: Definition Notation "Little-O" ( Small O)
Note: I will use the letter o (minuscula) for little-o; and O (capital letters) for big-O We say a function f is contained in o(g) if for all x it is true that f(x) < g(x). We say a function f is…
answered Gabriel 1,909