Posts by Lacobus • 13,510 points
596 posts
-
0
votes2
answers245
viewsA: Nested data class built from a dictionary
Foolishly, just strolling through the documentation of the standard Python library I discovered that since version 3.3, the module types provides a utility class called SimpleNamespace that is…
-
2
votes2
answers397
viewsA: LONG delay in requests.get Python
There’s nothing wrong with the Python nor with the library requests! Your repeated requests with this short interval of time between them are certainly making the "target" server understand that…
-
0
votes1
answer34
viewsA: How to group two indexes in a tuple?
If your intention is to retrieve a list of tuples that represent the coordinates of the board that are not filled in, follow an equivalent code capable of solving your problem: def…
-
2
votes1
answer65
views -
2
votes1
answer232
viewsA: Sqlite3 syntax error
It is not a good practice to "mount" your query string using strings literais formatadas. The method Cursor.execute() allows the use of placeholders for that purpose, look at this: Solution #1…
-
1
votes2
answers80
viewsA: Update Dict in List Comprehensions
Basic solution in which the list of dictionaries is updated in-place: from dateutil.tz import tzutc from datetime import timedelta, datetime MAX_DAYS_TO_INACTIVE = 15 MAX_DAYS_TO_EXPIRATION = 30…
-
2
votes2
answers77
viewsA: What can be done to improve my counting function?
Its counting method is basically an algorithm for calculating histogram, which is able to calculate the frequency at which each number repeats into a set of numbers. The standard library numpy has a…
-
1
votes2
answers28
viewsA: Input value equal to ID?
Assuming your data model is something like: CREATE SEQUENCE seq_id_cliente; CREATE SEQUENCE seq_id_venda; CREATE TABLE tb_cliente ( id BIGINT DEFAULT nextval('seq_id_cliente') PRIMARY KEY, nome TEXT…
-
1
votes2
answers222
viewsA: Save Date.now() to postgres
This whole number is the amount of milliseconds that have passed since the date of 01/01/1970 at 00:00:00 to date. Formally known as Unix age. Postgres is capable of converting an integer…
-
1
votes1
answer120
viewsA: How to display or extract all "cookie" information from a python page?
Attention, the cookie DV indicated in your question is contained in the request (Request), and not in the answer (Response)! Some cookies can be generated dynamically. Probably, some code JavaScript…
-
0
votes1
answer43
viewsA: Loop to append Googlesearch to multiple elements of a list
Following your own reasoning: from googlesearch import search Cities = ['Londres', 'Berlim', 'Paris', 'Moscou', 'Viena'] y = [] for x in Cities: links = [] for j in search(x, stop=3, pause=2):…
-
1
votes2
answers94
viewsA: How to make a replacement using the tuple list in python
The purpose of this exercise is to compare the characteristic of imutabilidade of primitive types list and tuples in Python. Just look at a possible step-by-step solution: # Um restaurante do tipo…
-
3
votes1
answer170
viewsA: How to scan the IP of a user-selected network, and show what is being used and what is available, in order. PYTHON
You should not worry about the operating system on which your program is running unless you have a reason very special! Python is a language portable and the solution to your problem can also be.…
-
1
votes1
answer29
viewsA: Escaping SQL "ILIKE" using bilbioteca psycopg2
Using the string concatenation operator ||: cur.execute("SELECT * FROM people WHERE name ilike '%%' || %s || '%%'; ", (name,)) Using the string concatenation function CONCAT(): cur.execute("SELECT *…
-
0
votes2
answers118
viewsA: Python move files to sub-folders of single name
You need to "assemble" a different directory name for each group of files you want to copy. Using date and time as a single directory name can cause all files to be copied to the same destination in…
-
3
votes1
answer130
viewsA: List containing only the last element in Python
You need to create an individual instance of Item for each row processed within its loop for, follows an example commented: # Objeto Item class Item: def __init__(self): self.palavra = None…
-
0
votes3
answers99
viewsA: Replace all arguments (of all strings) that exist in a Dict with . format
You can implement a recursive function capable of traversing all the keys and values of the dictionary in search of values that are of the type string only then apply the formatting, see only: def…
-
1
votes1
answer224
viewsA: Delete duplicate files
All indicates that you are not using the full file path that you want to copy/delete, the function os.path.abspath() can be used to make this "mounting". Alternatively, you can use the library…
-
1
votes2
answers82
viewsA: List ordering returns "None"
The method list.sort() just sort the list in-place and always returns None. An alternative would be to use the function sorted(), that returns an ordered copy of the list and does exactly what you…
-
3
votes2
answers54
viewsA: What does the # operator do before a parameter in the definition of a macro?
It is a preprocessing operator formally known as "Stringification Operator" or "Stringfication Operator". It is used in the body of a macro for the purpose of informing the preprocessor that the…
-
1
votes1
answer74
viewsA: Print elements of a regex in sequence in python
Certainly the BeautifulSoup is the most suitable library for your case, see: import sys import requests from bs4 import BeautifulSoup url =…
-
0
votes2
answers136
viewsA: Win function in Tic-tac-toe - Python
Your win function could check if one of the teams (X or O) was the winner, see only: def winner(paper, team): for i in range(3): # Horizontal if paper[0][i] == paper[1][i] == paper[2][i] == team:…
-
1
votes1
answer100
viewsA: Update lines in ods file using python
The method get_data() returns an instance of a OrderedDict, where your keys represent the spreadsheet and the value of each key is a list of lists, representing the two-dimensional matrix formed by…
-
10
votes2
answers421
viewsA: What is the default sorting (order) of the result of an SQL query?
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 MySQL, the order of…
-
0
votes1
answer159
viewsA: Function in struct in C
The problem is in the function ler(), who receives the parameter entrada by means of its value, that is, when it is called, the parameter entrada is "copied" into the scope of the function and…
-
0
votes1
answer1094
viewsA: Read Python Json file (beginner)
You can convert the list of dictionaries for a list dictionary filtering only the fields that interest you, see only: import json campos = ['nomeArq','percDif'] with open('teste.json') as f: entrada…
-
1
votes6
answers444
viewsA: Counting multiples of an integer is giving very different values than expected
In Python, you can solve the proposed problem without any kind of loop, look at you: n1 = int(input()) n2 = int(input()) count = len(range(n1, n2, n1)) print('O numero {} tem {} multiplos menores…
-
2
votes2
answers884
viewsA: Python - how to create a two-dimensional matrix with for loops
You are creating a list containing 10 elements. Each element in this list is an empty list, see only: x = [[] for _ in range(10)] print(x) Exit: [[], [], [], [], [], [], [], [], [], []] If you…
-
2
votes1
answer45
viewsA: Construction and Class Abstraction
The attributes ano and semana_completa sane variáveis de classe and need to be accessed as such: class TimeFlow: def __init__(self): ... self.mes = TimeFlow.ano[date.today().month - 1]…
-
0
votes1
answer29
viewsA: (Python) I also have a text file with a few words
Everything indicates that you are trying to calculate the histogram of the characters of the words contained in the input file. Assuming your input file is something like: Lorem Ipsum Dolor Sit Amet…
-
0
votes1
answer328
viewsA: Change the maximum values on a bar chart in Seaborn(barplot)
You need to recover the object instance of type Axes, representing the axes of the graph by means of the method matplotlib.pyplot.gca(). The object Axes has two methods: Axes.set_xlim() and…
-
2
votes1
answer115
viewsA: Split subdictionaries in python
You can convert your dictionary to a tuple list to enable block segmentation using the slicing on that list, check it out: def subdicts(dic, tam): tups = list(dic.items()) return [dict(tups[i: i +…
-
2
votes4
answers1648
viewsA: Count consonants in the sentence
You can combine the function strchr() of the standard library string.h with the function tolower() of the standard library ctypes.h to simplify your algorithm. The function strchr() traverse a…
-
2
votes1
answer52
viewsA: average population per city of each state
Your query is correct, your testing methodology is wrong: I even managed to run some searches but all gave numbers absurdly large What is big? What is small? What was the expected return value? The…
-
0
votes2
answers148
viewsA: Function that displays the characters of a repeating string
You can use the function strchr() of the standard library string.h to simplify your algorithm. The function strchr() traverse a string in search of the specified character and return NULL if the…
-
2
votes1
answer55
viewsA: Doubt about pointer and matrix
In C, the best way to display the address of a pointer is by using the conversion specifier %p in the format string of printf(). To get the address of a variable use the operator &, see just how…
-
-1
votes2
answers68
viewsA: How do I show the wrong input numbers?
You can build a function able to read the notes, treat them according to the rules set, display any errors and only return if the typed note is valid, see only: def obter_nota_aluno(msg): while…
-
1
votes1
answer24
viewsA: How to split the instance of a class through outrw
Here is a basic example capable of dividing the list of tuples livro in a list of dictionaries páginas, with the amount of keys quantidadeP: chaves =…
-
3
votes5
answers427
viewsA: How to run faster a code that calculates the number of factorial digits of a number?
You can use the kamenetsky’s formula to calculate the number of digits contained in the factorial of N, look at you: def kamenetsky(n): if n < 0: return 0 if n <= 1: return 1 x = (n * log10(n…
-
1
votes2
answers107
viewsA: python cleaning raw data manually
Assuming your input file is something like: Rosalind_6404 CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC TCCCACTAATAATTCTGAGG Rosalind_5959…
-
2
votes3
answers1145
viewsA: How to remove spaces from a string in Python without also removing line breaks?
An alternative solution would be: Break the string into rows; Remove whitespace from each line individually; Merge lines into a single string again. Look at that: entrada = ' testando \n minha \n…
-
1
votes2
answers94
viewsA: How to name the keys of a dictionary from a list (array)?
There is no guarantee that your dictionary keys would be renamed correctly! Python dictionaries do not support sorting of your keys! The closest you could come to this would be using the class…
-
2
votes1
answer59
viewsA: Why is error returned if you add a String with a Number?
Your premise is wrong, the concatenation between a variable of type str and another of the kind int not possible in Python! This type of operation throws an exception of type TypeError: $ python3…
-
1
votes1
answer89
viewsA: How to read an array of arrays and save each array[ ] into a different variable to run function with barplot?
Assuming that your array Two-dimensional input is something like: entrada = […
-
1
votes2
answers187
viewsA: Go through Array and remove words - Python
To read each line of a file (word) and add only lines that have sizes between 3 and 8 on a list: with open('senhas.txt') as f: words = [] for ln in f: ln = ln.strip() if 3 <= len(ln) <= 8:…
-
0
votes1
answer69
viewsA: I’m having trouble separating an integer from a variable
Solution 1) Passing parameters by reference (pointer): #include <stdio.h> void horario(int n, int *h, int *m, int *s) { *h = n / 10000; *m = (n % 10000) / 100; *s = n % 100; } int main(void) {…
-
1
votes2
answers202
viewsA: Force while loop output on C switch
If your code is inside a function, you could use return to get out, check it out: void foobar(void) { int opcao; while(1) { menu(); printf("\n"); printf("Opção selecionada: "); scanf_s("%d",…
-
3
votes1
answer453
viewsA: Warning error: format specifies type 'double' but the argument has type 'float *', C language
The function printf() are receiving %f in formatting string, and this requires a variable of type double or float in the formatting list. The Warning is happening because you are passing the address…
-
0
votes1
answer107
viewsA: Problems entering data into a table
First, your command of INSERT on the table dados will fail because violates the fields titulo and command who possess CONSTRAINTS of NOT NULL, that is, these fields cannot contain null values and…
-
-2
votes3
answers224
viewsA: Variable becomes string without reason
It turns out that the function input() returns a type variable str and this needs to be treated/converted properly to avoid this kind of confusion. Simplifying your idea: import random segredo =…