132 questions
1
vote
1
answer
133
views
Python raw material inventory optimizer
I want to build a function that can look at the raw material on hand information I provide, then come up with combinations of inputs to achieve a desired number of finished products.
on_hand_inventory ...
-1
votes
1
answer
103
views
Implement the __getitem__ method of a minimal collections.abc sequence with type hints
How does a minimal implementation of a Sequence from collections.abc, together with the correct type hints, look like?
According to its documentation, __len__ and __getitem__ are sufficient. My type ...
0
votes
1
answer
114
views
Is there a better way to zip iterables with mask?
I need to zip iterables with a personal mask function or just mask lists [True, False, ...]
from collections.abc import Callable
def zip_mask(a, b, mask):
iter_a, iter_b = iter(a), iter(b)
if ...
2
votes
1
answer
629
views
How to convert AsyncIterable to asyncio Task
I am using Python 3.11.5 with the below code:
import asyncio
from collections.abc import AsyncIterable
# Leave this iterable be, the question is about
# how to use many instances of this in parallel
...
0
votes
2
answers
2k
views
Import error with named tuple and Mapping
I have trying to fix an import error with the requests library in Python 3.11. This is to run a Discord bot that I have created. My original error is given as ImportError: cannot import name 'Mapping' ...
0
votes
1
answer
1k
views
How do i get top of the stack implemented using collections.deque
I am doing the Leetcode valid parenthesis question and want to implement the ans using deque stack.
there are three types of parenthesis {[()]} and i need to check the top of the stack before i pop it....
0
votes
0
answers
134
views
Code module returning "unhashable type: list" error when sending result through Fast API
I've written a python code to check the unique values of the specified column names from a pandas dataframe.
Main Code:
Checking the unique values & the frequency of their occurence
def uniq_fun(...
0
votes
1
answer
157
views
Inheriting from type and typing.Mapping: "TypeError: descriptor '__subclasses__' of 'type' object needs an argument"
I am trying to define a class that is supposed to simultaneously do two things:
serve as the metaclass for a dataclass
act like a mapping
i.e., it will need to be derived from both type and typing....
2
votes
1
answer
62
views
Fast way to create a nested dictionary from a list of tuples without a for loop
I know similar questions have been asked before but I cannot find an adequate answer to my situation.
Let's say I have the following list of tuples:
d = [('first', 1), ('second', 2), ('third', 3)]
I ...
0
votes
1
answer
87
views
list of tuples to single list
I have list of tuples in the following format,
[('ABC', ['32064', ['WOO', 'MISSI']]),
('XYZ', ['32065', ['HAY']])]
I need to convert them into following format,
[['ABC','32064','Woo'],
['ABC','32064',...
-1
votes
2
answers
195
views
In python, how can I create & maintain a list of IP addresses indexable by a pair of IP addresses?
I'm looking for a way to maintain and update a list of IP addresses that I can index into (via a pair of IP addresses) to add a new address to the list.
For example, suppose I have an arbitrary index ...
1
vote
1
answer
578
views
Create a dictionary by entering a word and its meaning then print it at the end
This is the question:
and this the output that is required:
This is code I have written so far:
class_list = []
keys = []
meanings = []
def script():
key = input("Enter the word: ")
...
1
vote
1
answer
308
views
`dict.pop` ignores the default value set by `collections.defaultdict(default_factory)`
Python's dict.pop(key[, default]) ignores the default value set by collections.defaultdict(default_factory) as shown by the following code snippet:
from collections import defaultdict
d = defaultdict(...
-5
votes
1
answer
45
views
Why iterating on a collection does not require index? [duplicate]
I'm trying to sort my confusions learning python.
>>> cities = ['London', "Toronto", 'Paris', 'Oslo']
>>> cities
['London', 'Toronto', 'Paris', 'Oslo']
>>> for i ...
0
votes
1
answer
143
views
Python runtime error with dictionary for loop when appending value list
I am trying to make a contact list/phone book in python 3.10 with a dictionary and list and have been trying to add a feature to add a searched contact that isn't inside of the phone book. The current ...
1
vote
1
answer
134
views
Python list comprehension optimization
I have used during a problem this piece of code to retrieve the count of each element in a list :
nums = [1,1,3,2,3,3,4,1,1,4,2,3,3,2,1,3,4,1,2]
print([nums.count(num) for num in set(nums)])
This ...
2
votes
2
answers
582
views
How to sort the frequency of each letter in a descending order Python?
import collections
MY_FUN_STR = filter(str.isalpha, (str.lower("ThE_SLATe-Maker")))
frequencies = collections.Counter(MY_FUN_STR)
a = sorted(frequencies, reverse=True)
for letter in ...
0
votes
1
answer
550
views
Use namedtuple instead of tuple with typing.optional
How can I use namedtuple with typing.optional instead of this tuple ?
I want to to call the function in the format of result_final(power=Stats(min=12, max=None))
Thank you.
I tried with Stats = ...
0
votes
2
answers
195
views
How to use proper container in python
For the following code I would like to use a structure in order to not have to give 2 values for each element min and max and also I would like to have a container if exists to can give one value and ...
0
votes
2
answers
744
views
How to store a collection of constants that can be called by Collection.variable?
I'm searching for a collection that can be used to store multiple constants and also can be used to get a list of them?
EDIT: It does not have to be constants, it can be variables.
I want to get a ...
0
votes
1
answer
665
views
What's the time complexity of Python's collections.Counter.total()?
What's the time complexity of Python's collections.Counter.total()? I've read the documentation for the method, but there's not mention of its efficiency. Does anyone know how the method is ...
3
votes
2
answers
14k
views
max on collections.Counter
The max on collections.Counter is counter intuitive, I want to find the find the character that occurs the most in a string.
>>> from collections import Counter
>>> c = Counter('...
0
votes
0
answers
48
views
Get list items that don't match most frequent value
I have a list of dictionaries looking like this:
[{'customer': 'Charles', 'city': 'Paris'}, {'customer': 'John', 'city': 'New York'}, {'customer': 'Jean', 'city': 'Paris'}]
I tried something using ...
1
vote
1
answer
2k
views
Sequence vs. MutableSequence
I've been using Sequence in type hints for sequences including mutable lists. Now I've just discovered that there is also MutableSequence. As far as I can tell, Sequence is a superclass of ...
87
votes
12
answers
295k
views
ImportError: cannot import name '...' from 'collections' using Python 3.10
I am trying to run my program which uses various dependencies, but since upgrading to Python 3.10 this does not work anymore.
When I run "python3" in the terminal and from there import my ...
0
votes
1
answer
400
views
What is the difference between getattr() and calling the attribute?
Here is a code I have written. I presumed both of them to return the same answer but they don't! How are they different?
from collections import deque
d = deque()
for _ in range(int(input())):
...
0
votes
2
answers
635
views
Python append to list replacing all previous indexes with last value
In the following Python 3 code, the correct value is written into the daysSchedule but when iterating to the next value.
class Data:
def getDaysSchedule(scheduleUrl, filterTeam = ''):
...
0
votes
1
answer
974
views
TypeError: 'type' object is not iterable when iterating over collections.deque that contains collections.namedtuple [closed]
I made a simple replay buffer that when I sample from it gives me the error TypeError: 'type' object is not iterable
import collections
import numpy as np
Experience = collections.namedtuple("...
1
vote
1
answer
423
views
Python 3.9.5: One dictionary assignment is overwriting multiple keys [BUG?]
I am reading a .csv called courses. Each row corresponds to a course which has an id, a name, and a teacher. They are to be stored in a Dict. An example:
list_courses = {
1: {'id': 1, 'name': '...
0
votes
1
answer
189
views
How to access internal dictionary of collection.Counter to extend the functionality of Child class by using Inheritance?
I want to add 2 functions in collections.Counter to add functionality to it for sorting and returning minimum n values. For this to work, I need to access the internal dictionary and I don't know how ...
3
votes
2
answers
1k
views
Collections.counter() is counting alphabets instead of words
I have to count no. of most occured word from a dataframe in row df['messages']. It have many columns so I formatted and stored all rows as single string (words joint by space) in one variabel ...
0
votes
3
answers
5k
views
How to use Counter in python without showing numbers
I have little problem with python's Counter library. Here is an example:
from collections import Counter
list1 = ['x','y','z','x','x','x','y', 'z']
print(Counter(list1))
Output of it:
Counter({'x': 4,...
0
votes
1
answer
77
views
In Python why does the following code give incorrect answers when the list is sorted and list is un-sorted?
I am trying to sort a list based on the frequency of it's elements. But I get two different answers when the list is sorted and list is un-sorted. Please see the code segment below.
Could someone ...
6
votes
2
answers
7k
views
Python defaultdict(default) vs dict.get(key, default)
Suppose I want to create a dict (or dict-like object) that returns a default value if I attempt to access a key that's not in the dict.
I can do this either by using a defaultdict:
from collections ...
0
votes
1
answer
153
views
Class Initialization of a list of empty lists not updating
I have a list that is made up of 4 deques with a set length. I have made that list with the hope that it will update as the other ones. Here is a simple example:
class foo():
def __init__(self):
...
0
votes
0
answers
362
views
Python `UserString` seems problematic?
I need to use UserString to create my own str class, but its implementation seems problematic.
For example, in the class definition, it reads:
def __eq__(self, string):
if isinstance(...
10
votes
1
answer
6k
views
Is collections.abc.Callable bugged in Python 3.9.1?
Python 3.9 includes PEP 585 and deprecates many of the types in the typing module in favor of the ones in collections.abc, now that they support __class_getitem__. This is the case with for example ...
0
votes
2
answers
80
views
Why is the time taken by collections.Counter to construct a frequency map less than a simple dict creation by a for loop? [closed]
From what I understand, since count() iterates over the list again for each element it is slower. Since, the Counter and dict construction both iterate over the list once
shouldn't the dict ...
2
votes
1
answer
672
views
Summing up collections.Counter objects using `groupby` in pandas
I am trying to group the words_count column by both essay_Set and domain1_score and adding the counters in words_count to add the counters results as mentioned here:
>>> c = Counter(a=3, b=1)
...
0
votes
3
answers
1k
views
How to fill a tuple with a for loop
I am trying to fill a tuple with named tuples using a for loop.
The example code below works:
import collections
Experiment = collections.namedtuple('Experiment', ['parameter', ])
nsize = 3
...
3
votes
2
answers
499
views
Combinations with Replacement and maximal Occurrence Constraint
from itertools import *
import collections
for i in combinations_with_replacement(['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'],15):
b = (''.join(i))
freq = collections....
-3
votes
2
answers
812
views
Python's `collections.Counter` with non-integer values
collections.Counter is extremely useful to gather counts and operate on counts as objects. You can do things like:
>>> Counter({'a': 2, 'b': 5}) + Counter({'a': 3, 'c': 7})
Counter({'c': 7, '...
1
vote
1
answer
183
views
Way to achieve str.strip()-like behaviour with iterable Python-objects [closed]
Which is the way is to achieve str.strip()-like behaviour with list, tuple and similar iterable objects in Python?
Examples:
str.strip()-like
>>> lst = ['\t', 0, 'a', ' ', 0, '\n', '\n', '', '...
4
votes
4
answers
4k
views
Algorithmic complexity to convert a set to a list in python
In python, when I convert my set to a list, what is the algorithmic complexity of such a task? Is it merely type-casting the collection, or does it need to copy items into a different data structure? ...
0
votes
2
answers
133
views
Last added element value reflected in whole list in python - How to solve this problem?
The following is my data:
"Jay": 1, "Raj": 1,"Jay": 3,"Raj": 3,"Jay": 10,"Raj": 2,"Jay": 2
I would like to put it into a list to make it look like this:
["Jay": 1,"Raj": 1,"Jay": 3,"Raj": 3,"Jay": ...
1
vote
2
answers
8k
views
How to access elements in a dict_values?
I have a dict :
{49: {'created_at': '2018-11-07T13:25:12.000Z', 'url': 'https://www.test.com'}}
I would like to get 'created_at'.
I've attempt through different methods but without a success... I ...
0
votes
1
answer
137
views
Iterating over a Pandas Dataframe column and adding its elements to a Python Collections Counter object
I have a pandas dataframe of N columns of integer object values. The values in the columns are associated with outcome of a particular random experiment. For example, if I were to call df.head():
...
0
votes
0
answers
31
views
Given a set, perform a pairwise operation on every element of the set? [duplicate]
Assume I have a set:
s = {1,2,3,4,5}
And now I want to perform an operation of every possible unordered pair of that set, say addition. For a list I would do:
for i in range(len(s)):
for j in ...
-1
votes
1
answer
710
views
Why does the set function in Python produce different outputs for the same inputs? [duplicate]
This is my code
string='AABCAAADA'
k=3
for i in range(0,len(string),k):
print(set(string[i:i+k]))
each time I run it produces a different output. how can i fix this?
outputs:
{'B', 'A'}
{'A', 'C'...
1
vote
3
answers
178
views
Most pythonic way to check list boils down to one value
I want a function check to check that a given list reduces ("boils down") to exactly one value under a given function reduce_function. (A common example could be to check that a list of lists contains ...