Posts by Miguel • 29,306 points
758 posts
-
0
votes1
answer33
views -
2
votes2
answers195
viewsA: How to return a list where the size is set according to a number typed in the python input?
One of the problems with code (and perhaps the only one without having tested) is that you are not changing (increasing) the value of j, so you always end up with the same values. What are Twin…
-
1
votes1
answer25
viewsA: How to pull the values of an input if it has a certain value - PHP
I’m going to assume you want the indices where those values are to then access those same values, in which case you’ll be taking an unnecessary turn You can obtain your own values by using…
-
1
votes1
answer24
viewsA: How to return the last record of each sale
Try the following: SELECT venda, max(data) from foo group by venda;
-
0
votes1
answer248
viewsA: Using regex to convert latitude and longitude coordinates of degrees/minutes/direction to decimal in python
Using this as a basis: https://www.pgc.umn.edu/apps/convert And having: Latitude Longitude 0 27º59' N 86º55'E I think you can start by creating a function for DDM to DD conversion, note that since…
-
3
votes1
answer126
viewsA: Fastest way to iterate over lines in python, pandas
Having the following original dataframe: Código Data Pedido Meia Metade Num. Pedido Preço Quantidade Sabor 0 600 10/01 Sim 1 1000 40.0 1 Calabresa 1 600 10/01 Sim 2 1000 32.0 1 Mussarela 2 601 08/09…
-
2
votes1
answer113
viewsA: Error when using If parole
I think you’re complicating more than is really necessary. Having: import pandas as pd from io import StringIO csv = StringIO("""DATE;time;pair;type;ordertype;price;cost;fee;vol;margin;misc…
-
2
votes2
answers63
viewsA: How do you compare an item with all other items in the same list (with dictionaries inside) in a pythonic way?
If the intention is only pedagogical you can make a group by 'manual', and go adding: dados = [ {"Codigo": 1, "Valor": 300.00,}, {"Codigo": 1, "Valor": 300.00,}, {"Codigo": 2, "Valor": 400.00,},…
-
1
votes1
answer47
viewsA: Return array object with condition
You can do it like this: var objeto = [ { "apelido": ["Lukas", "Vintage", "Vintage Culture"], "nome": "Vintage Culture", "title": "Cassian - Magical ft. Zolly (Vintage Culture Remix)", "link":…
-
1
votes1
answer43
viewsA: Update input value with Bootstrap touchspin
You must track the event change which happens in the input to which the bootstrap-touchspin is associated. You can do it like this: $("#P1103_QTDE").TouchSpin({ min: 0, max: 10000000000, boostat: 5,…
-
2
votes4
answers361
viewsA: How to count occurrence of strings within a dictionary made up of lists in Python?
If this is always the format of the counts you can also: pesquisa = {'PEDRO': ['FANTA',5,'PEPSI',4],'ANA': ['SPRITE',5,'COCACOLA',4], 'DIEGO': ['INTEL', 7, 'PYTHON', 8, 'WINDOWS', 9, 'LINUX', 10]} c…
-
0
votes1
answer2111
viewsA: How to convert values into percentage of a "total" column into pandas?
Try this: import pandas as pd df = pd.DataFrame({ 'a': ['Data Analisis', 'Machine Learning', 'Data Visualisation', 'Big Data', 'Deep Learning', 'Data Journalism'], 'b': [1688, 1629, 1340, 1332,…
-
3
votes3
answers1495
viewsA: Merge elements from a list with the last different tab
You can do it by omitting the cycle: def join_list(lista): str = ', '.join(lista[:-1]) # gerar uma string com os items separados por virgula, com excecao do ultimo return '{} and {}'.format(str,…
-
1
votes1
answer59
viewsA: Return to category the RGB difference is smaller
You can try making the sum of the absolute difference between each color in the list and the color you want to check which has the lowest difference of the reference color: from math import sqrt def…
-
1
votes1
answer1662
viewsA: Replace Nan value in dataframe with a string
Answering the question title, you can use the method fillna: ... df = df.fillna('fórmula genérica') ... Or: ... df.fillna('fórmula genérica', inplace=True) # atribui o novo valor ao df teres de lhe…
-
3
votes2
answers178
viewsA: Format output in txt file
You can write in exactly the same line where you found these cousins. Suggesting another way to do but getting the expected result: def verificaPrimo(num): return all(num%i!=0 for i in range(2,num))…
-
5
votes1
answer48
viewsA: Select checkbox and show a select
What you want is for select to be hidden by default (by clicking), and this action will only happen in the click depending on your code. You can do this two ways: CSS: select[name="Acompnhante"] {…
-
3
votes1
answer88
viewsA: display the result of a foreach outside the loop
You have a bit of a mistake in $p[i] whereas i does not exist (nor $p at that point, but in php an array can be declared when it is first populated). Taking advantage of the code with but due fixes:…
-
2
votes1
answer549
viewsA: Pandas: How to merge two data frames?
You have the most direct way, whose solution was inspired here (several examples of sql converted into pandas), in this case we want the left join or outer join in this case: import pandas as pd df1…
-
5
votes1
answer611
viewsA: Renaming files with date in python
My advice is to simply rename increasingly, as putting the date as suffix/prefix (eg dd-mm-yyy_hh:mm:ss) in a cycle like this example would risk many files with equal names (would be changed in the…
-
1
votes2
answers926
viewsA: limit the number of digits Entry - Tkinter
This is an example code for a maximum of 5 digits: from tkinter import * def on_write(*args): s = var.get() if len(s) > 0: if not s[-1].isdigit(): # retirar ultimo caracter caso nao seja digito…
-
7
votes1
answer1373
viewsA: How to add values of a csv using Python?
Your mistake, at least the one that stands out most, is that you are going through every state in the North in every record, which is two, and adding up the number of inhabitants of that line twice.…
-
3
votes1
answer41
viewsA: Replacing an index with a string
If you store in an array you will have more flexibility to handle/precess the data the way you want, in this case include a separator <br> among the elements var nums = []; for(var i=1;…
-
3
votes5
answers10820
viewsA: How to Reverse a String?
Java is not my strong suit but I’ll leave here the recursive version to invert a string: class Main { public static void main (String[] args) throws java.lang.Exception { String str = "miguel";…
-
4
votes1
answer527
viewsA: How to make a parallel system call in python?
You can use threads to execute processes in pararelo. I will put here the simplest example depending on the code you provided: import threading import time # por motivos de demonstracao def…
python-3.xanswered Miguel 29,306 -
5
votes2
answers2434
viewsA: Check each file size in a Python folder with 'os'
You should check the file size by file and not from a file list. To check the size of each file in a directory you can use getsize, that basically returns os.stat(ficheiro).st_size, and is in bytes,…
-
2
votes1
answer332
viewsA: Check url after request
In order to see which url of the last request you made (taking into account that we will follow the redirects), you do: ... response.url # ultimo request feito, destino do ultimo redirecionamento…
-
1
votes1
answer205
viewsA: Get input value
If you want to do with regex: import re html = '<input type="hidden" name="authURL" value="1526610106833.UG2TCP2ZiJ9HKXhlrlgybcdEBB0=" data-reactid="37"/>' match = re.compile('name="authURL"…
python-3.xanswered Miguel 29,306 -
12
votes4
answers4581
viewsA: How to multiply in Python without the multiplication operator?
This can all be done from a single function and without recursion, using absolute values abs(): def multiplica(i, j): res = 0 while i > 0: res += j i -= 1 return res i = int(input('Digite o…
-
3
votes1
answer53
viewsA: How to proceed with batch execution for python methods
That’s because exemplo01 is a function, while i is a string, although it has the same function name, my advice is to use a dictionary to map the key (key, in this case the same function name) to the…
-
1
votes1
answer115
viewsA: python - Print, by line, the letter and nickname append()
It’s almost there, but the variable iniciais it’s not making much sense, if you want to print that content you can do it in for: escritores = [['Pedro', 'Tamen'], ['Almeida', 'Garrett'], ['Camilo',…
-
2
votes3
answers288
viewsA: Search for tuple in an array
You can try it like this: a = [('FI', 'SE'), ('SE', 'DK'), ('DK', 'DE'), ('DE', 'PL'), ('PL', 'BY')] b = [['NL', 'DK', 0], ['NL', 'DE', 0], ['NL', 'BE', 0], ['FI', 'SE', 0.054]] search1, search2 =…
-
1
votes1
answer46
viewsA: Python - Complete list of each writer, along with the acronym of each person (first letter of name and surname)
If you already have the list of writers, to print the full name and acronym of each you can do: escritores = [['Pedro', 'Tamen'], ['Almeida', 'Garrett'], ['Camilo', 'Pessanha'], ['Almada',…
-
3
votes1
answer294
viewsA: python - Print the list elements ending with the letter 'a'
The logic to 'grab' the last element of each name (last letter) is the same (nome[-1]). Since a string in many languages is also an iterable, and python does not escape the rule: To print all names…
-
4
votes3
answers2068
viewsA: PYTHON- Program that prints on screen all numbers divisible by 7 but not multiples of 5, between 3000 and 3200 (inclusive)
It’s doing a lot of unnecessary things (and I don’t really understand why), you can use the module to see if the rest of the i by 7 is 0, and if the rest of the division of i by 5 is different from…
python-3.xanswered Miguel 29,306 -
8
votes2
answers2726
viewsA: Recursive function to return string backwards
The error is happening because you are checking whether "test" (string) is less than 10 (?? ), I think what you want is the string length (number of characters): ... if len(palavra) < 10: ... But…
-
2
votes2
answers322
viewsA: How to implement Fibonacci more efficiently using dictionaries?
I’m not sure what you mean by "implement with dictionaries," but here’s an iterative way that’s much faster: def F(n): a, b = 0, 1 for i in range(n): a, b = b, a+b return a Maybe with dictionaries…
-
3
votes1
answer1889
viewsA: How do I filter data by date on a dataframe (Python)
Try the following: races = pd.read_csv('races.csv', parse_dates=['date']) # tratar a coluna date como datetime results = pd.read_csv('results.csv') last10M = pd.merge(results, races, how='outer',…
-
3
votes2
answers77
viewsA: Return pieces of an eternal
Here’s what you can do: def chunker(iterable, size): for i in range(0, len(iterable), size): # percorremos o nosso range com um step de 4 neste caso, [0, 4, 8, 12, 16, 20, 24] yield…
-
2
votes1
answer577
viewsA: Return form with data after Validator failure
Apparently it’s all right, except for one thing missing, old(): In the form values you should put, ex: <input type="emais" class="form-control" value="{{old('email')}}" name="email" id="email"…
-
5
votes3
answers892
viewsA: Date and Time in Datetime format
Here’s what you can do: 1 - We use strtotime() to convert into Unix timestamp; 2 - We use date() to convert this timestamp to the desired format: <?php $data = '17-04-2018'; $hora = '16:12';…
-
2
votes1
answer4081
viewsA: How to break a list and turn it into an array in Python?
Using numpy: import numpy as np lista = np.arange(1, 10).reshape(9, 1) print(lista) ''' array([[1], [2], [3], [4], [5], [6], [7], [8], [9]]) ''' Now we can do: lista = lista.reshape(3, 3)[::-1] #…
-
2
votes1
answer172
viewsA: On big scrapings how to avoid Connectionerror?
Testing and changing the structure to use threads is a lot of pags to use just one, unless you have time. In my opinion, either you choose the columns to store in csv, or it simply stays in a json…
-
3
votes3
answers3778
viewsA: Count the most popular words
Actually, there are two things that you’re not aware of, The Return causes the function to return (stop the execution) right after that line, and there is a detail that is escaping you, the commas…
-
4
votes2
answers776
viewsA: Compare values in a list of tuples
Two weeks is a long time since you can solve in 1/2 lines d: lista = [('Thiago', 30, 9.0), ('Maria', 28, 7.0), ('Ana', 30, 9.0)] ordered = sorted(lista, key=lambda x: (x[2], x[1], x[0]))…
-
4
votes2
answers1256
viewsA: Client and server programming: How to achieve numerous data exchanges per client and multiple clients simultaneously?
Problem 1: There is only "1 data exchange per connected client!" ; there are several, depending on the size of your mailing list to be sent/received by the customer. Problem #2: The server only…
-
20
votes2
answers872
viewsA: Program to simulate the anniversary paradox
From the description of the problem, I believe you’re doing some unnecessary things, it’s simpler than it seems. What is the birthday paradox/problem? Video explanatory PT To simulate this we can do…
-
1
votes1
answer1253
viewsA: How do I prevent user input from resulting in a Valueerror, and ask the program to redo the question
You can avoid’re-calling' input(). The solution to this (no Trigger exception) conventionally passes through a block try/catch: try: int(input("Digite a quantidade de cabos: ")) except ValueError as…
python-3.xanswered Miguel 29,306 -
1
votes2
answers2568
viewsA: Change the value of a number in a matrix without knowing the position (index) in Python
The line numero <= 4 doesn’t make much sense, it’s doing absolutely nothing. Remember that you have a list of lists, so the logic inside the for is is not correct, you must access two indices,…
-
2
votes3
answers3080
viewsA: Check the line containing a string inside a TXT file
Here’s what you can do: with open('Arquivo.txt') as f: for l_num, l in enumerate(f, 1): # percorrer linhas e enumera-las a partir de 1 if 'laranja' in l: # ver se palavra esta na linha…