Posts by Pedro von Hertwig Batista • 3,434 points
117 posts
-
1
votes2
answers586
viewsA: How to count repeated elements in a list of tuples?
The easiest way is to use one Counter, standard library class collections. It acts as a dictionary and can be initialized with a list, or in this case a generating expression: from collections…
-
0
votes3
answers73
viewsA: Key-value dictionary
As mentioned, a key is unique, but nothing prevents you from having a list as a value, so you can store multiple elements per key. For consistency and simplicity, I would use a defaultdict list:…
-
1
votes1
answer65
viewsA: Web Scrapping Python
Using the browser developer tool window opened in the "network" tab while using the site for a box, we see that the request has changed to URL "https://www.banco24horas.com.br/ajax.php". If we try…
pythonanswered Pedro von Hertwig Batista 3,434 -
0
votes1
answer677
viewsA: How to pick up element xpath in span
The first step in scraping is to search for an official API. In the case of this site, has a link at the bottom of the page informing the request routes. If I hadn’t: You cannot get the text because…
-
1
votes1
answer44
viewsA: Panda does not create new lines in Spreadsheet
I could not play the problem with a valid list, the following works: import pandas as pd df = pd.DataFrame({'NAME':['Pedro', 'Joaquim'],'OAB':['123', '321']}) writer =…
-
0
votes1
answer596
viewsA: Request sending json
There is a difference between using the parameter json and the parameter data, maybe you’re confusing the two. In a POST request, the headers and the "body" of the message are sent. In the case of…
-
1
votes1
answer150
viewsA: How to encode a number with the notation x and not 0x
The function hex gives you a string representation of the bytes passed to it, and this representation begins with 0x to indicate that it is a hexadecimal number. When you create a variable with b'',…
-
4
votes2
answers536
viewsA: Add values between ICT
Seems like a good use for collections.Counter: from collections import Counter ct_db = {u'AB-00': 18, u'RR-00': 14, u'LD-00': 56, u'SR-00': 33, u'YT-00': 452} ct_db2 = {u'CD-07': 26, u'RR-00': 223,…
-
2
votes3
answers141
viewsA: Amounts of games in a betting code and their random numbers in ascending order in Python
You can use the function sorted to get the ordered version of a list, which by default is increasing: def loteria(): jogo = list(range(1, 60)) random.shuffle(jogo) print("--- Número da sorte ---")…
pythonanswered Pedro von Hertwig Batista 3,434 -
2
votes2
answers110
viewsA: Compare dictionary key with an integer
I imagine the exercise is for educational purposes, but it is worth pointing out that the Counter, of the standard library collections, is a good tool for this case: from collections import Counter…
-
2
votes1
answer87
viewsA: Algorithm for certain letter combination
The function combinations, of the standard module itertools, gives you all possible combinations for a given sequence and window size: import itertools ... In [6]:…
-
1
votes1
answer37
viewsA: Problems with excessive search requests on google
Google is notoriously difficult to crawl and employs several anti-bot measures. Here has some tips that help a little, but still the maximum cadence is very small. What I suggest is to use the API…
-
0
votes1
answer89
viewsA: Base conversion
The easiest way to obtain a hexadecimal representation is to transform the value in question into bytes and call its function .hex(). Since you are not dealing in your "memory" with really binary…
-
1
votes1
answer172
viewsA: Loop Replace all string characters by python list character
We can use a collections.deque so we can easily create a "rotated" version of the alphabet. Then just take the position of each letter in the alphabet and apply the equivalent position in the…
-
2
votes2
answers414
viewsA: Store a dictionary in a Python file
The pickle stores the data in a binary format recognized only by Python. This causes two problems with the code you are using: The opening mode of the programme shall be "wb". of "binary writing"…
-
4
votes3
answers42
viewsA: How to simplify these two methods?
You can create a function that accepts the operation (sum, subtraction or other) as argument, and then call this function by modifying only the desired operation. Since we do not have the direct…
-
4
votes1
answer63
viewsA: A function that does the opposite of an addition mod 2³²
Module (remaining split) is not a reversible operation. Let’s consider the simplest case with the operator %: In [1]: 9144835390 % 2**32 Out[1]: 554900798 Here we observe that the operation is the…
-
2
votes2
answers1297
viewsA: What is the difference between string.split(',') and string.rsplit(',') in python?
The difference appears when passing the optional argument maxsplit. It determines the maximum number of divisions to be made. In the case of split, the algorithm starts from the left and the…
-
4
votes2
answers528
viewsQ: In Python, is there any way other than `numpy` and `float('Nan')` to get the special constant`Nan`?
I’ve been reading the website of Underhanded C Contest, in which the goal is to write subtly malicious code that looks normal at first glance. One of the common techniques mentioned was the use of…
pythonasked Pedro von Hertwig Batista 3,434 -
2
votes2
answers142
viewsA: Manipulation of items during iteration
This section of the documentation has relevant information. What happens is not very intuitive, but it is easily explained. When iterating over a list, each item is assigned, one at a time, to an…
-
3
votes3
answers3324
viewsA: Ignore if it is uppercase and lowercase in the string
You have to compare both versions in lower case (or upper case). The function .lower() of a string transforms all characters into its lowercase versions: n1 = input('Qual é o seu bolo favorito?') if…
-
1
votes1
answer166
viewsA: Lambda function for Dict Dict - Python
The generation inline of dictionaries is made through a dictionary comprehension: data_json = {'events': [{'event':'a', 'foo': 'bar'}, {'event':'b', 'foo': 'baz'}, {'event':'a', 'foo': 'bax'}]}…
-
2
votes1
answer326
viewsA: Python does not insert data in sqlite3
Missed the commit to save bank changes. ... result = cursor.execute(comando) conexao.commit() # Salvar return result
-
2
votes2
answers63
viewsA: Not all arguments were converted during string formatting. What does that mean?
Missing one % before the 0.1f. The = there is also unnecessary and would give problem. Do: f.write('%0.1f\n'%(count)) Or with format: f.write('{:.1f}\n'.format(count))…
pythonanswered Pedro von Hertwig Batista 3,434 -
1
votes2
answers180
viewsA: Find values in a list that are equal to the index they are in. How to optimize?
Your algorithm has an important bug. Documentation: list.index(x[, start[, end]]) Return zero-based index in the list of the first item Whose value is Equal to x This means that your algorithm only…
-
2
votes1
answer224
viewsA: Application of linear regression
The sklearn supposes that your data X be a list list, because otherwise it has no way to distinguish between a dataset of, for example, 8 Features and 1 example and a dataset of 1 Feature and 8…
pythonanswered Pedro von Hertwig Batista 3,434 -
0
votes1
answer33
viewsA: How do I sum up the values stored in the list: pairs?
Use the function sum. soma = sum(pares)
python-3.xanswered Pedro von Hertwig Batista 3,434 -
1
votes1
answer1217
viewsA: Grouping table groupby pandas
You can use the value_counts to find out which of the column values Material have more than one input, and then filter your Dataframe by these values: import pandas as pd import io dados =…
-
2
votes3
answers1219
viewsA: What is wrong with the Python code?? Bhaskara
Its denominator is incorrect. The denominator in Bháskara’s formula is 2*a, and not 2*c: # Errado: divisao = 2 * c divisao = 2 * a # Certo Also, you will have problems when the roots are imaginary,…
pythonanswered Pedro von Hertwig Batista 3,434 -
1
votes1
answer1277
viewsA: Multi-value dictionary creation for a key
You can register a tuple. To create a tuple, the two variables must be wrapped in parentheses: dic.update({'nome': (variavel1, variavel2)}) It is also important to remember that when referencing a…
pythonanswered Pedro von Hertwig Batista 3,434 -
0
votes1
answer500
viewsA: Json by python URL?
This is not how you open a json file. First you must open the file, and then use json.load to load its contents. See: import json with open('file.json', 'r') as fd: meu_dicionario = fd.load(fd) That…
pythonanswered Pedro von Hertwig Batista 3,434 -
1
votes1
answer2052
viewsA: How to create a local network (intranet) with Django?
Instead of running python manage.py runserver Perform the following: python manage.py runserver 0.0.0.0:80 This instructs Django to open the server and accept local IP connections from your machine.…
-
1
votes1
answer226
viewsQ: How to detect a click or other mouse event in win32gui’s Notifyicon?
I’m trying to modify the library win10toast so that I can pass a callback that runs when the user clicks on the Windows 10 notification that I show. The "meat" of the library, which I’ve mastered as…
-
2
votes1
answer266
viewsA: Selenium + Python error when using time.Sleep()
This seems to be a problem of geckodriver 0.21.0, if using this version. Try to use the 0.20.1 for the time being.…
-
2
votes1
answer1844
viewsA: How to change a specific word in a TXT by another
Your code doesn’t make much sense for what you’re asking for. You don’t need to use regular expressions for your case, and neither split. Just the replace, which is the most basic method that does…
-
2
votes1
answer526
viewsA: How to Force Finish a Thread in Python?
You can use the asyncio, in which coroutines/tasks (Task) are similar to threads but are not really threads as defined by the OS, and so have no problem changing context or state outside of their…
pythonanswered Pedro von Hertwig Batista 3,434 -
0
votes1
answer120
viewsA: Find a certain word in a particular Tweepy user
This is because you require, in your list comprehension, that the text be exactly equal to the keyword: ... for tweet in alltweets if tweet.text == 'palavra_chave'] If you want to verify that the…
-
3
votes2
answers872
viewsA: How to know how many numbers in one list are repeated in others?
The structure set has the function intersection, which returns the intersection between the set and another element, such as a list. We can easily define a function that simply transforms one of the…
-
3
votes2
answers196
viewsA: Multiplication and division result with two boxes after the comma
This is because by default, when printing floats like this, Python tries to use scientific notation to shorten the result. You can force it to give you the full result using {:.2f} instead of just…
-
12
votes3
answers343
viewsA: Regular Expressions: Lazy quantifier function "?"
You get the same result because the $ force the end of the capture group to be at the end of the string. Thus, the smallest possible number of times still goes necessarily to the end of the string.…
regexanswered Pedro von Hertwig Batista 3,434 -
2
votes1
answer1078
viewsA: How to break a list into two distinct lists to use in Gnuplot python?
I don’t know gnuplot, but it’s not difficult to separate your list into two lists with values x and y in Python. The first step is to break down the elements from the ' t''. For this, just use…
-
2
votes1
answer159
viewsA: How to delimit plotting area in python?
Just pass the parameter bbox_inches='tight': plt.savefig('meuGrafico.png', dpi=300, bbox_inches='tight')…
-
4
votes1
answer163
viewsA: How to remove a specific character from some specific strings within a Python list?
You can use the replace to replace unwanted characters in your string with an empty string: '#[Header]'.replace('#', '') # '[Header]' To do this in all strings in the list, just use a list…
-
4
votes1
answer6892
viewsA: How to save figure in Python with matplotlib?
When you do plt.show(), the figure is zeroed to prepare another graph. So, call savefig results in the blank image you obtained. You have two options: Call savefig before show:…
-
0
votes2
answers1039
viewsA: Geometric Progression in python
That’s right. The first step is to get input from the user. For this, we use the function input. entrada_str = input('n: ') # '232' Unfortunately, this gives us a string, which is useless for our…
pythonanswered Pedro von Hertwig Batista 3,434 -
0
votes2
answers55
viewsA: Find the index in a value-based array of dictionaries
To check if the key value 'word' corresponds to 'value2': palavra1.get('palavra') == 'valor2' # True This prevents you from having one KeyError by accessing a key that does not exist. Knowing this,…
pythonanswered Pedro von Hertwig Batista 3,434 -
3
votes3
answers465
viewsA: Test sum function
For a function to be executed, you have to call it: def soma (x, y): return (x + y) def testa_soma(): if (soma(10, 20) == 30): print ('correto') testa_soma()…
-
1
votes2
answers3426
viewsA: Importing library in python
When the import gets gray, it’s because you’re not using it. What I suspect you’re doing is this: import time sleep(2) It doesn’t work because you’re only importing the name time. To use the…
-
1
votes1
answer57
viewsA: Why doesn’t print return all the items in a list?
Your formatted code is as follows: cars = ['audi','bmw','subaru','toyota'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title()) The problem is that the else is at the wrong…
-
0
votes1
answer19
viewsA: How do I print information in the same place as the previous information?
To make a load bar, install and use the tqdm. In the command window (cmd) or terminal emulator: pip install tqdm Code: from tqdm import tqdm import time for i in tqdm(range(100)): # Seu código de…
python-3.xanswered Pedro von Hertwig Batista 3,434