Posts by Lacobus • 13,510 points
596 posts
-
0
votes2
answers64
viewsA: How to select methods in a function and add results in a list?
You could create a dictionary by associating your Identifiers with the corresponding functions to avoid the block if/elif/else. Look at that: # Dicionario associando o identificador # com a…
-
0
votes2
answers106
viewsA: Saving csv file using python
You can write the output file directly into the format .xlsx. First install the module openpyxl: $ pip3 install openpyxl Now, use the following code: import pandas as pd entrada = 'dados.csv' saida…
-
1
votes5
answers3780
viewsA: I want to know how many rows and columns an array has in Python?
You can calculate the dimensions of your 2D matrix using basically the technique: nlinhas = len(m) ncolunas = len(m[0]) Note that the number of columns is calculated by obtaining the amount of…
-
0
votes1
answer175
viewsA: Python only reads the last word of my Wordlist
You’re making three mistakes in your code: 1) You need to return the cursor of the password file to the beginning: file_pass.seek(0) 2) For each line read, the line break character needs to be…
-
2
votes2
answers61
viewsA: Get the number of files contained in a directory
The standard bibilioteca os provides a very complete and portable interface of access to the operating system file system. Instead of using the method os.system() to execute specific commands, you…
-
0
votes3
answers347
viewsA: Create list with the sum of consecutive equal numbers
You can use the function groupby() of the standard library itertools, look at you: from itertools import groupby entrada = [1,2,2,2,3,4,4] saida = [sum(i) for _, i in groupby(entrada)] print(saida)…
-
3
votes2
answers78
viewsA: Invert a string correctly
A classic example of this algorithm can be found in the famous book The C Programming Language (Chapter 3, page 55-56): #include <string.h> void inverter(char * s) { int c, i, j; for (i = 0, j…
-
1
votes1
answer117
viewsA: Use composite key as PK or not?
I don’t think it’s necessary to create a composite primary key in your pay table. If a Serviço Contratado may have multiple Pagamentos, to cardinality between these entities would be one-to-several…
-
3
votes3
answers896
viewsA: How to insert a character in the middle of the sentence
You can solve your problem in a rather "pythonic" way using a generator combined with a state machine, look at you: def substituir(string): ultimo = None for atual in string: if atual == ultimo:…
-
1
votes4
answers1133
viewsA: Add negative elements from a list
You can use a comprehensilist on to filter the list elements with values less than zero and then add them with the function sum() look at you: lista = [12, -2, 4, 8, 29, 45, 78, 36, -17, 2, 12, 8,…
-
3
votes2
answers78
viewsA: Help to parse data and turn it into a dictionary
You can combine operations with strings and regular expressions to build a parser that is able to extract the information in the desired format. Look at an example: import re def parse(s): ret = {}…
-
1
votes2
answers739
viewsA: How to read line break into C file?
Unfortunately there is no function in the standard library capable of interpreting literal strings for its equivalent escape sequence. An alternative would be to implement a function capable of…
-
0
votes2
answers74
viewsA: How I see the code of an already interpreted html page
Something like this can be done in Python with the library Selenium, the code would look something like this: from selenium import webdriver browser = webdriver.Firefox()…
-
2
votes2
answers187
viewsA: How to turn a set into a Python 3.x list
You can use the class method set of diferença simétrica: result = m.symmetric_difference(n) Or the equivalent operator ^: result = m ^ n For example: a = '2 4 5 9' b = '2 4 11 12' n = set(int(i) for…
-
0
votes2
answers123
viewsA: How to find a string in a python txt
You can divide your problem into two parts. The first part would be responsible for loading the contents of the file fully into memory, putting together a list of dictionaries, see only: def…
-
0
votes3
answers613
viewsA: Show python position of prime only
You can use the native function enumerate() which is capable of receiving a list or any other object everlasting as parameter and return a generator of tuples containing the index and its respective…
-
4
votes2
answers245
viewsQ: Nested data class built from a dictionary
Consider the following: implementation: from abc import ABC # Base class DictModel(ABC): def __init__(self, model=None): if model: for k, v in model.items(): if isinstance(v,dict): setattr(self, k,…
-
0
votes3
answers99
viewsA: Sum of groups in an SQL
I don’t know if I understand your question correctly, but if you wish to recover the total amount of hours per secretary, the thing may be simpler than it seems. Assuming you have a data structure…
-
1
votes1
answer91
viewsA: I’m new to programming, how do I get out of sequential foma returns?
Follow a code suggestion able to solve your problem, see only: import calendar import datetime entrada = input() agora = datetime.datetime.now() anos = [(int(ano), calendar.isleap(int(ano))) for ano…
-
0
votes1
answer51
viewsA: How to instantiate a constructor variable (to be Primary key) within the table?
Inheritances are beautiful in theory, but are a hell in practice. An excellent alternative is the use of a coluna discriminadora, which is actually a foreign key that points to the type of that…
-
1
votes2
answers145
viewsA: SELECT RANGE 1 IN 1 HOUR - POSTGRESQL
You came pretty close to solving the problem, look at that: SELECT t_id, time FROM t WHERE date_trunc('hour',time) = time; Exit: | t_id | time | |------|----------------------| | 1 |…
-
1
votes1
answer42
viewsA: Empty processes in the queue - Postgresql
Those empty cases may be operations carried out from a ROLE other than the one used to make your query. That is, you do not have privileges to view the operations performed by others users of the…
-
1
votes2
answers86
viewsA: How does ORDER BY draw columns in case of a repeated value?
The pattern SQL does not guarantee that the recovered data has a standard ordering. Without a ORDER BY specific, the order of its results will always be undetermined. In the PostgreSQL, the order of…
-
2
votes1
answer1454
viewsA: Difference between EXISTS and IN in postgres?
Assuming you have something like: CREATE TABLE a ( id INTEGER, descricao TEXT ); CREATE TABLE b ( id2 INTEGER ); INSERT INTO a ( id, descricao ) VALUES ( 1, 'alpha' ); INSERT INTO a ( id, descricao…
-
1
votes2
answers1331
viewsA: write struct to file
1) You are not sure in what context your program is running from xcode and hence, your output file is being written somewhere "unknown" on your file system. Ensure that the output file will be…
-
1
votes1
answer83
viewsA: What would be the ideal unique natural key associated with a person?
You are starting from the premise that the only solution to your problem is to use a field containing a numerical code extracted from an official document as a single key but you forget who not all…
-
1
votes2
answers112
viewsA: Abstract methods do not require implementation
Your premise is wrong. In C++ there is no way to "force" the implementation of a method (virtual or purely virtual) in a given class in the inheritance chain. The only rule is that all virtual…
-
2
votes2
answers724
viewsA: Delete a space allocated by malloc
You can use the function memmove() of the standard library string.h combined with the function realloc() of the standard library stdlib.h, Just look at the solution to your case: registro * lista =…
-
2
votes1
answer71
viewsA: What is the most efficient way to kill an external process from a program written in C?
Assuming you are on a UNIX family operating system, the function kill() of the system library signal.h, can solve your problem. However, the function kill() is only able to send signals to a process…
-
0
votes3
answers246
viewsA: Read and print struct values
You can implement a registration function that is able to register an amount n of employees, check it out: void inserir( funcionario * func, int qtd ) { for( int i = 0; i < qtd; i++ ) { cout…
-
0
votes2
answers42
viewsA: How to place multiple ordered outputs in a table
You can implement a function capable of printing your table with a parameterized amount of columns, see only: void exibir_tabuada( int ncolunas ) { int i = 0; int j = 0; int coluna = 0; int linha =…
-
0
votes1
answer30
viewsA: Sequential reading of data from a file
Assuming that your input file alunos.txt be something like: 5 ZE CARLOS 8.5 10.0 ANTONIO SANTOS 7.5 8.5 SEBASTIAO OLIVEIRA 5.0 6.0 ISAAC NEWTOW 4.0 2.5 ALBERT EINSTEIN 10.0 10.0 We can abstract the…
-
0
votes2
answers86
viewsA: String problem in C, term exclusion in string, through string comparison
You can use the functions strstr() and memmove(), both from the standard library string.h. The function strstr() can be used to search for the term within the sentence and the function memmove() to…
-
1
votes3
answers141
viewsA: Amounts of games in a betting code and their random numbers in ascending order in Python
You can modify your draw function so that it is able to draw a specific amount of games, returned a array two-dimensional, look at that: import random def loteria( qtd ): jogos = [] dezenas = list(…
-
2
votes3
answers108
viewsA: Problems with a C program
I worked out the solution of the problem using part of his reasoning however, I implemented the code aiming to readability for a better understanding of the proposed algorithm, see: #include…
-
1
votes1
answer148
viewsA: Stack assignment problems in Python
You are declaring class attributes Elemento statically, this causes each Elemento use the same memory space to store the attributes proximo and numero, making it impossible to create the dynamic…
-
0
votes4
answers2153
viewsA: Function to invert a string
You can invert a string inplace without making use of any standard library function, making use of only of pointer arithmetic, look at you: void reverse( char str[] ) { char * ptr = str; while( ptr…
-
0
votes1
answer276
viewsA: Floating rand in C matrix
The function rand() of the standard library stdlib.h generates only pseudo-random numbers whole amid 0 and RAND_MAX. A generic solution would be to implement a function capable of generating…
-
2
votes3
answers1952
viewsA: Sum of the main diagonal of a matrix in Python
How about using the numpy: import numpy as np def SomaDiagonal( m, invertida=False ): x = np.asarray( m ) if( invertida ): x = np.fliplr(x) return np.trace(x) matriz = [ [1,2,2], [4,1,6], [2,8,1] ]…
-
2
votes3
answers573
viewsA: incompatible types when assigning to type ‘tipoNo’ {aka ‘struct tipoNo’} from type ‘tipoNo *’ {aka ‘struct tipoNo *’} arv = inserir(&arv, 5);
Since your structure has members of its own type, you will need a forward declaration before its full definition, see only: typedef struct estruturaNo tipoNo; // forward declaration struct…
-
0
votes1
answer167
viewsA: Add bash output to text
You can use the utility date to recover the system time and format it as needed, for example: $ date +"%F %T" Exit: 2019-04-22 14:20:18 To save the output of the utility to a text file without…
-
1
votes2
answers2087
viewsA: Problem with perfect number in C
According to Wikipedia, a perfect number is a natural number for which the sum of all its own natural divisors (excluding itself) is equal to the number itself. For example, number 28 is perfect…
-
1
votes2
answers37
viewsA: Redefining how a function operates? C
The keyword typedef is intended to associate a name to a guy. It is a widely used language construct to simplify the declaration syntax of complex data structures, providing more descriptive…
-
0
votes2
answers150
viewsA: Select with IN operator in array column in Postgres
Assuming your table is something like: CREATE TABLE tb_livros ( id SERIAL PRIMARY KEY, titulo TEXT, ids_autores INT[] ); Containing the following data: INSERT INTO tb_livros ( titulo, ids_autores )…
-
1
votes3
answers2356
viewsA: Access data from a JSON structure
You can use the function loads() module json which is able to read a string containing data in JSON format and convert it to a primitive data structure composed basically of listas and dicionários,…
-
0
votes1
answer522
viewsA: Counters in the Mergesort
You can create a structure to encapsulate your counters, see: typedef struct detalhes_s { int comps; /* Quantidade de comparacoes */ int trocas; /* Quantidade de trocas */ unsigned long duracao_us;…
-
0
votes2
answers109
viewsA: Error with memcpy and memset
You are not initiating all memory allocated with malloc(), the call of memset() is filling with zeros only the first bytes of your buffer. The operator sizeof() will not return the memory region…
-
2
votes1
answer159
viewsA: Repeat(while) structure conversion in C to Assembly mips
You can use the GNU Compiler Collection to generate the code Assembly equivalent to the program originally written in language C. Assuming you’re in an architecture x86, you will need a version of…
-
1
votes1
answer372
viewsA: How to mirror an image?
Whereas your image is something like: /* Imagem 13x10 */ char image[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,…
-
0
votes2
answers332
viewsA: Treatment of Python Images
Following the line suggested in the comment of the colleague @carlosgadinni, the use of a service of Cloud Storage could be a very versatile solution and scalable for your problem. Cloud storage…