Posts by Woss • 73,416 points
1,476 posts
-
5
votes1
answer534
viewsA: How to remove list item within loop?
First, do not use range(0, len(lista)) to scroll through a Python list, just do item in lista which is more idiomatic, readable and faster. Second, do not use the name list for variable; since it is…
-
2
votes2
answers2303
viewsA: Random Choice in python
To read the table value, we will keep the question code: numero = int(input('Digite o número da tabuada: \n')) If we want the table 1 to 10, we draw a factor in this interval: fator =…
-
1
votes1
answer216
viewsA: Sort 2D vector in descending order
Just use the method sort defining the parameter key: a.sort(key=lambda l: l[2], reverse=True) See working on Repl.it | Ideone Thus, the list a shall be ordered by taking into account the third value…
-
1
votes1
answer222
viewsA: Manipulating dictionaries within other dictionaries
Simply filter the dictionary values based on the course, getting the name of each student: nomes = (aluno['nome'] for aluno in Alunos.values() if aluno['curso'] == 'SI') And to display the names:…
-
1
votes4
answers208
viewsA: Identify missing value in numerical sequence
Assuming that the cards numbered from 1 to N are sequential; that is, a 5-card deck would have face 1, 2, 3, 4 and 5, then the solution is trivial using the class set python. Just define the two…
-
2
votes3
answers1806
viewsA: Add the first "n" elements of a Python geometric progression
Mathematics [O(1)] The general term of a geometric progression is given by: Thus, the sum of n first terms would stand: That if you apply the general term, you get the equation (1): If we multiply…
-
3
votes4
answers4581
viewsA: How to multiply in Python without the multiplication operator?
Another option is to use the native function sum: def multiply(a, b): result = sum(b for _ in range(abs(a))) return result if a > 0 else -result See working on Repl.it | Ideone | Github GIST In…
-
0
votes1
answer117
viewsA: Python Guess Game
It is difficult to say what is wrong with your code, or even what could be improved, because the indentation of your code in the question damaged the understanding. If you can edit the question by…
-
5
votes2
answers1328
viewsA: Vectors names and ages - Python
The logic is quite simple, but a little laborious. Having the two lists, one of names and another of ages, follows: Search for the youngest in the age list; Find the position in the list where the…
-
15
votes3
answers844
viewsA: How to initialize a list of empty lists?
The problem of the code you tried to make: lista = [[]]*n Is that the object that will be repeated, [], is initialized only once, when defined its reference and this is used in the other positions.…
-
2
votes1
answer155
viewsA: Search dates among other dates in Python
I believe it is enough for you to use the method find, which returns a cursor, not just a record, passing a dictionary as a filter for its date field. For example: inicio = datetime.date(2018, 4,…
-
1
votes2
answers101
views -
7
votes2
answers2238
viewsA: Timeout in Python input function
The function signal.alarm is only available for Unix environment. You can use the module signal. First, we have defined a function that will treat the case of the user being inactive and their time…
-
8
votes3
answers23189
viewsA: Recursive and iterative function that calculates the factorial from 1 to n
In fact, the most efficient option in this case is to use the concept of memoization in the function, since the factorial of any number n can be obtained by fatorial(n-1) * n and how all factor…
-
3
votes1
answer410
viewsA: Python: loop screenshot saving over
Because the file name is only set once, when the code is started. Thus, all screenshots will have the same name and consequently overwrite the previous file. To avoid this, you need to update the…
-
1
votes3
answers90
viewsA: How to "break" the PHP variable and bring separate results
As commented, you can do this only with the functions array_map and explode, still with the array_filter to remove possible unwanted results: function relacao_tipo_metragem($tipo, $metragem) { if…
-
1
votes1
answer50
viewsA: Iteration with variable of type 'TIME'
The way it is, you’re not working with schedules, you’re working with string. For us it turns out to be the same thing, but for the computer they are completely different. To work with schedules,…
-
3
votes2
answers110
viewsA: Is it wrong to have a class with only methods?
Wrong is a very strong word (2). I will implement my functions disguised as methods because ... If you can finish this sentence, then it is at least acceptable to do so. There is no way to define a…
-
7
votes4
answers26369
viewsA: Find certain text in a string
Your code has two important considerations that were not addressed satisfactorily in the other answers. 1) Redundancy in function input. If you read the official documentation of the function, you…
-
6
votes2
answers487
viewsA: how can I make a simple python Russian roulette
If you want the repetition to stop when the "died" value is drawn, just make a conditional structure: while contador < 6: print('atirando...') acao = random.choice(list_morte) print(acao) if acao…
-
3
votes1
answer57
viewsA: Remove index spaces in a list
You can define a generator that will take the non-null genres from your data, then iterate it, printing the result. For example: genres = (columns[6] for columns in data if columns[6]) for genre in…
-
1
votes1
answer1396
viewsA: Renaming bulk files from a notepad list
If I understand correctly, what you need to do is just: import os with open('nomes.txt') as nomes: for nome in nomes: antigo, novo = nome.strip().split(';') os.rename(antigo, novo) print(f'Arquivo…
python-3.xanswered Woss 73,416 -
3
votes2
answers3007
viewsA: Identify the day of the week of a given date
This issue can be solved easily with the library datetime, creating an object date representing the date and a timedelta representing the time interval to be considered. from datetime import date,…
-
2
votes1
answer82
viewsA: list index out of range - From Fortran to Python
See an excerpt of your code with some comments: 1 D = [] 2 # ↳ Aqui você definiu D como uma lista vazia 3 4 u_med = [] 5 # ↳ Aqui você definiu u_med como uma lista vazia 6 7 delta_r = [] 8 # ↳ Aqui…
-
2
votes1
answer817
viewsA: Implement numerical sum with successor and predecessor only
To simplify the answer, I will only consider that entries will be non-negative integers. It is given that there are two operators in the used numerical system where I will represent as x+ the…
-
2
votes1
answer401
viewsA: Sum Total Hours Overdue
You can do this easily with the native class DateTime: $d1 = new DateTime('2018-04-23 11:20:33'); $d2 = new DateTime('2018-04-23 08:01:00'); $atraso = $d1->diff($d2); echo…
-
6
votes1
answer403
viewsA: How to invert the side that starts the digits in an HTML input?
Do not use direction: rtl for that. Although it produces the expected result, it hurts the semantics of HTML, since the purpose of RTL is to indicate that the content of that element is in a…
-
13
votes2
answers3036
viewsA: How to check which file is the latest in a Python folder?
You can use the module pathlib. from pathlib import Path data_criacao = lambda f: f.stat().st_ctime data_modificacao = lambda f: f.stat().st_mtime directory = Path('/seu/diretorio') files =…
-
1
votes2
answers90
views -
3
votes2
answers131
viewsA: Loop logic with for
The syntax of the loop for is: for ([inicialização]; [condição]; [expressão final]) declaração And the order of execution is: Initialization; Checks the condition; If the condition is true, executes…
-
15
votes4
answers6745
viewsA: How to implement a recursive MDC calculation algorithm in Python?
The non-recursive solution could be rewritten as: def mdc(a, b): while b: a, b = b, a % b return a print(mdc(70, 25)) # 5 See working on Repl.it | Ideone | Github Gist The recursive version could be…
-
4
votes2
answers77
viewsA: Return pieces of an eternal
Miguel’s solution works, but it has limitations. The first is that it is necessary to convert the generator to list when passing as parameter, which already hurts the requested in the statement,…
-
3
votes1
answer74
viewsA: Method to return string from an integer value
The main problem in your code is that your string expects two values, but you are indicating only one. You need to calculate the number of weeks and the surplus of days, that comes to complete a…
-
3
votes2
answers75
viewsA: Program that gives a secret number using bisection search
Complementing the response of Pedro von Hertwig, who pointed out the error of his code. Can you notice that you used in your code four times the function input exactly with the same message? This is…
-
6
votes2
answers7177
viewsA: How to repeat the code at the end in python?
Since you’re learning, it’s worth commenting on. What you did in your code was basically relate four variables to their respective values and, at first, they will not vary during execution.…
-
10
votes1
answer471
viewsQ: How can you check if the number is in between so fast?
It is known that with the module timeit it is possible to measure, in Python, the execution time of code snippets. Curious, I was testing what is the time it takes to verify if a certain number is…
-
13
votes1
answer471
viewsA: How can you check if the number is in between so fast?
In fact, considering only the object of type range, the time to check whether a given value belongs to the range is, in the rating big-O, O(1), which means that it will be constant regardless of the…
-
4
votes3
answers713
viewsA: Print the largest substring of s where the letters occur in alphabetical order
The idea may be much simpler than it seems and, incidentally, this is an issue that was proposed in a job interview in some large company in the industry, I can not remember right if Google or…
-
1
votes2
answers38
viewsA: Quantity of elements that has at least the reported value
In PHP, it’s better to worry about simplicity than performance, since the language itself was not created to be fast, but rather to simplify some tasks. In this case, just use the function…
-
1
votes1
answer306
viewsA: Error in requests with aiohttp in asyncio
There’s a much simpler way to solve this. First, let’s define an asynchronous function that will be responsible for making the request, using the module aiohttp: async def fetch(url): async with…
-
2
votes2
answers1715
viewsA: python list problems
Another solution, simpler, but running away from what was explicitly requested by the statement, would be to create an object namedtuple to represent a particular car instead of storing the values…
-
3
votes1
answer39
viewsA: How do I add a new value to an array?
Just make the union of the two arrays: what you already have and what has the values you want to add: foreach ($Read->getResult() as $PDT) { $pdt_promo[] = array_merge($PDT, ['Outrovalor' =>…
-
1
votes1
answer38
viewsA: Array of objects in php, objects being overwritten, why?
How is creating the instance $obj outside the loop, you will have the same reference in all iterations, overriding the old values. This envelope is mirrored into the array $menu because PHP adds to…
-
6
votes1
answer168
viewsA: Program to convert mp3 using multiprocessing module is looping
For now I owe you the error in your code, because I will need to analyze more time, but an alternative to the problem is to use the module asyncio, since the processing itself of your program runs…
-
4
votes2
answers11799
viewsA: What does float("Nan") and float("inf") mean in Python?
Just to complete the answer of the Isac that did not comment directly on the code snippet of the question (which is not exactly the focus, but it is interesting also to know), in functions that…
-
3
votes1
answer479
viewsA: How to write a calendar in alphabetical order of Names using Python Ordereddict?
Apparently, you read some data as long as the user wishes and then display them all in alphabetical order based on the name. It will be easier for you to create a dictionary for each record and…
-
0
votes4
answers81
viewsA: Succinct conditional structure with multiple comparisons
If it is something constant in the project, I would recommend creating a function for it. Even, it would be possible, in addition to the suggestions in the other answers, to use the function…
-
4
votes2
answers3158
viewsA: Write a python script that reads an 8-digit integer
The best way to solve it is: numero = input('Número: ') if len(numero) == 8: print(sum(map(int, numero))) else: print('NAO SEI') Which could even be reduced to: numero = input('Número: ')…
-
0
votes2
answers101
viewsA: Can you do it with less variables?
To read the sequence, just modify a little the answer I published in: Accept only numerics in input numeros = [] while True: try: numero = int(input("Informe um número inteiro positivo: ")) if…
-
2
votes1
answer83
viewsA: Get String Type Data from a CSV Document
When you read a CSV file, the object row in: for row in read: ... will be a list of all found columns. As your file has only one column with the email, the value of row will be a list with an…