text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : I have a 2d array , and I have some numbers to add to some cells . I want to vectorize the operation in order to save time . The problem is when I need to add several numbers to the same cell . In this case , the vectorized code only adds the last . ' a ' is my array , ' x ' and ' y ' are the coordinates of th...
How to vectorize increments in Python
Python : I have got a chunk of code likewhere a and b are arrays of the same length , a is given ( and big ) , func is some function that has a lot of local variables but does not use any global variables . I would like to distribute computations of func across several CPUs . Presumably I need to use multiprocessing mo...
Parallelizing multiplication of vectors-like computation in python
Python : When I changed to : I found the second code is much more efficient , why ? bench mark it , and in my situation ranks is an numpy array of integer . The difference is much more.output : <code> for i in range ( 0 , 100 ) : rank = ranks [ i ] if rank ! = 0 : pass for i in range ( 0 , 100 ) : rank = ranks [ i ] if...
in python why if rank : is faster than if rank ! = 0 :
Python : Recently I ran into cosmologicon 's pywats and now try to understand part about fun with iterators : Ok , sorted ( a ) returns a list and sorted ( a ) == sorted ( a ) becomes just a two lists comparision . But reversed ( a ) returns reversed object . So why these reversed objects are different ? And id 's comp...
Understanding iterable types in comparisons
Python : While looking for a pythonic way to rotate a matrix , I came across this answer . However there is no explanation attached to it . I copied the snippet here : How does it work ? <code> rotated = zip ( *original [ : :-1 ] )
How does this code snippet rotating a matrix work ?
Python : Is there any bulid-in function in python/numpy to convert an array = [ 1 , 3 , 1 , 2 ] to something like this : <code> array = [ [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 1 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 1 , 0 ] ]
How to covert 1d array to Logical matrix
Python : I have time series data in the following format , where a value indicates an accumulated amount since the past recording . What I want to do is `` spread '' that accumulated amount over the past periods containing NaN so that this input : Becomes this output : Is there an idiomatic Pandas way to do this rather...
Pandas idiomatic way to custom fillna
Python : I 'm trying to create a recursive generator in Python , but I 'm doing something wrong . Here 's a minimal example . I would expect the function f ( ) to return an iterable that would give me all the positive numbers > = n.Why is the iteration stopping after the first number ? <code> > > > def f ( n ) : ... yi...
Why Recursive Generator does n't work in Python 3.3 ?
Python : Given the following simple regular expression which goal is to capture the text between quotes characters : When the input is something like : The capturing group ( 1 ) has the following : I expected the group ( 1 ) to have text only ( without the quotes ) . Could somebody explain what 's going on and why the ...
Strange behavior of capturing group in regular expression
Python : I wrote some small code for controlling multiple compute engine on google cloud platform . The whole file is here in github.The part causes problem is gcloud compute ssh in the followingThis part is for uploading the same file ( usually .zip ) to all instances with same tag . However doing it on my local compu...
How to avoid gcloud compute alerting store the key in cache
Python : I 'm reading a file ( while doing some expensive logic ) that I will need to iterate several times in different functions , so I really want to read and parse the file only once.The parsing function parses the file and returns an itertools.groupby object.I thought about doing the following : However , itertool...
Using itertools.tee to duplicate a nested iterator ( ie itertools.groupby )
Python : I am trying to add dictionaries which have a key from each element from the list and value ( s ) from one following element from the list and a count for the number of times it follows it , in dictionary format . For example , if we have the list of words , [ 'The ' , 'cat ' , 'chased ' , 'the ' , 'dog ' ] and...
Making a dictionary for value in a dictionary in Python
Python : Using pandas v1.0.1 and numpy 1.18.1 , I want to calculate the rolling mean and std with different window sizes on a time series . In the data I am working with , the values can be constant for some subsequent points such that - depending on the window size - the rolling mean might be equal to all the values i...
Pandas rolling std yields inconsistent results and differs from values.std
Python : I am trying out the list comprehensions . But I got stuck when I tried to write a list comprehension for the following code.output for this is : Is it even possible to write a list comprehension for this code ? if it is how would you write it ? <code> a = [ ' x ' , ' y ' , ' z ' ] result = [ ] for i in a : for...
List comprehension for multiplying each string in a list by numbers from given range
Python : I discovered a slightly strange corner of Python I was hoping to get some help understanding . Suppose I have a class B that I want to attach as a method for class A. I can do : When I call a.B ( ) , in the B.__init__ I get a self object for a new B instance.Now suppose I want to capture the actual value of th...
Attaching class as method
Python : I would like to slice a dataframe to return rows where element x=0 appears consecutively at least n=3 times , and then dropping the first i=2 instances in each mini-sequenceis there an efficient way of achieving in pandas , and if not , using numpy or scipy ? Example 1Desired output : Example 2x=0 ( element of...
slice pandas df based on n consecutive instances of element
Python : I 'm quite new at TensorFlow . I 'm using TF 1.8 for a 'simple ' linear regression.The output of the exercise is the set of linear weights that best fit the data , rather than a prediction model . So I would like to track and log the current minimum loss during training , along with the corresponding value of ...
Can I log training loss via a hook with a LinearRegressor ?
Python : To better understand Python 's generator I 'm trying to implement facilities in the itertools module , and get into trouble with izip : My code uses the ERROR line , and the reference implementation ( given in the manual ) uses the OK line , not considering other tiny differences . With this snippet : My code ...
Why does this implementation of izip ( ) not work ?
Python : So I 'm taking a programming course in high school , right now and I am making a program of a game that the teacher assigned for all of us make . The game is called `` game of sticks '' ( if you would like a better run down on how the game works skip about half way through this video https : //www.youtube.com/...
Python 3 need help in a school project
Python : I 'm trying to use SQLAlchemy to write a query like this : My data table has 3 columns , parent_id , date_time and value.I 've spend few hours already and there 's no way I can get it to work exactly like above.The closest I 've got ( at least semantically it make sense ) is : But its not working , it 's not p...
How to join subquery results to function results
Python : I 've been working extensively with dates in python/django . In order to solve various use-cases I 've been blindly trying a variety of different approaches until one of them worked , without learning the logic behind how the various functions work.Now it 's crunch time . I 'd like to ask a couple of questions...
Django/python - dispelling confusion regarding dates and timezone-awareness
Python : Why exactly isprinted by the following code ? In particular : Why is C.__init__ ( ) not printed ? Why is C.__init__ ( ) printed if I put super ( ) .__init__ ( ) instead of A.__init__ ( self ) ? <code> A.__init__ ( ) B.__init__ ( ) D.__init__ ( ) # ! /usr/bin/env python3class A ( object ) : def __init__ ( self ...
Why is an __init__ skipped when doing Base.__init__ ( self ) in multiple inheritance instead of super ( ) .__init__ ( ) ?
Python : I am making a library that deals with Python modules . Without getting into details , I need a list of the common Python module extensions.Obviously , I want .py , but I 'd also like to include ones such as .pyw , .pyd , etc . In other words , I want anything that you can import.Is there a tool in the standard...
Is there an easy way to get all common module extensions ?
Python : I 've currently got a list of tuples ( though I control creation of the list and tuples , so they could be altered in type if needed ) . Each tuple has a start and end integer and a string with an ID for that range 's source . What I 'm trying to do is identify all of the overlapping ranges within the tuples.C...
Identify all overlapping tuples in list
Python : Lets say I want to use gcc from the command line in order to compile a C extension of Python . I 'd structure the call something like this : I noticed that the -I , -L , and -l options are absolutely necessary , or else you will get an error that looks something like this . These commands tell gcc where to loo...
Return the include and runtime lib directories from within Python
Python : I have data in pandas dataframe with 1 minute time step . This data is not recorded continuously , now I would like to split all my data into separate event based on the condition below : If there is continuous data recorded for 5min or more then only it is considered as a event and for such event data need to...
Calculating event based on the continuous timestep
Python : I 'm attempting to make a short program that will return the factorial of a number , which works fine . The only problem I am having is getting the program to end if the user inputs a non-integer value . <code> num = input ( `` input your number to be factorialised here ! : `` ) try : num1 = int ( num ) except...
ending a program early , not in a loop ?
Python : I have a pandas dataframe with name of variables , the values for each and the count ( which shows the frequency of that row ) : I want to use count to get an output like this : What is the best way to do that ? <code> df = pd.DataFrame ( { 'var ' : [ ' A ' , ' B ' , ' C ' ] , 'value ' : [ 10 , 20 , 30 ] , 'co...
Groupby in Reverse
Python : Can anyone explain me the output of following python code : Testing the function <code> from theano import tensor as Tfrom theano import function , shareda , b = T.dmatrices ( ' a ' , ' b ' ) diff = a - babs_diff = abs ( diff ) diff_squared = diff ** 2f = function ( [ a , b ] , [ diff , abs_diff , diff_squared...
Neural Networks : Understanding theano Library
Python : I have a dataframe like this : Further , I have a variable max_sum = 10.I want to assign a group to each row ( i ) based on the value in keys and ( ii ) the max_sum which should not be exceeded per group.My expected outcome looks like this : So , the first two values in the a group ( 1 and 5 ) sum up to 6 whic...
How to assign groups based on a maximum sum ?
Python : I have implemented a function in R to estimate the Gaussian Process parameters of a basic sin function . Unfortunately the project has to be made in Python and I have been trying to reproduce the behavior of R library 's hetGP in python using SKlearn but I have a hard time mapping the former to the later.My un...
Reproducing R 's gaussian process maximum likelihood regression in Python
Python : I have an `` interface '' that will be implemented by client code : run should in general return a docutils node but because the far far mostcommon case is plain text , the caller allows run to return a string , which will bechecked using type ( ) and turned into a node.However , the way I understand `` Python...
How can I balance `` Pythonic '' and `` convenient '' in this case ?
Python : Input to pd.read_clipboard ( ) Code : Output : Questions : Why that � in the last row ? How to modify more than 1 column in 1 line ? Python Version : 2.7 , Pandas : 0.19 , IPython : 4 <code> Ratanhia ,30c x2 , 200c x2Aloe ,30c x2 , 200c x2Nitric Acid ,30c x2 , 200c x 2Sedum Acre ,200c x2 , 30c x2Paeonia ,200c ...
Error in parsing , update multiple columns in 1 line
Python : I have three arrays called RowIndex , ColIndex and Entry in numpy . Essentially , this is a subset of entries from a matrix with the row indexes , column indexes , and value of that entry in these three variables respectively . I have two numpy 2D arrays ( matrices ) U and M. Let alpha and beta be two given co...
Is there a faster way to do this pseudo code efficiently in python numpy ?
Python : I have been playing with Python these days , and I realize some interesting way how Python assign id ( address ) to new instance ( int and list ) . For example , if I keep call id function with a number ( or two different number ) , it return the same result . e.g.Also when I declare the variable first and the...
Python reference to an new instance alternating
Python : fairly new to Python here . Have this code : I originally used raise `` Negative Number ! '' etc but quickly discovered that this was the old way of doing things and you have to call the Exception class . Now it 's working fine but how do I distinguish between my two exceptions ? For the code below it 's print...
Python , distinguishing custom exceptions
Python : Given a list of regions on a line : I want to know which regions a point X belongs to : I know naively ( and my current implementation ) we can just search in O ( n ) , but a more dramatic use case with thousands of regions ( and thousands of look up points , really , is the motivator ) justifies investigating...
Optimized approach to finding which pairs of numbers another number falls between ?
Python : In Python 2 , are all exceptions that can be raised required to inherit from Exception ? That is , is the following sufficient to catch any possible exception : or do I need something even more general like <code> try : code ( ) except Exception as e : pass try : code ( ) except : pass
Does ` try ... except Exception as e ` catch every possible exception ?
Python : I read a cool article on how to avoid creating slow regular expressions . Generally speaking it looks like the longer and more explicit and regex is the faster it will complete . A greedy regex can be exponentially slower . I thought I would test this out by measuring the time it takes to complete a more compl...
Python Regex slower than expected
Python : I have a string : I want to convert it to : I am trying this : but it returns : ( without the string operation done ) What is the possible reason .title ( ) is not working . ? How to use string operation on the captured group in python ? <code> str1 = `` abc = def '' str2 = `` abc = # Abc # '' re.sub ( `` ( \w...
String Operation on captured group in re Python
Python : If I try the following code , I see that the normal block return value is not returned , but the finally block return value is : A more advanced example is to call a function in each return statement : In that situation , I can see that : In the normal block , the show function is evaluated ( but not return ) ...
Is it an error to return a value in a finally clause
Python : Writing doctests for a method that abbreviates a dictionary by searching for a passed key word in the keys of the original dictionary , and returning the new , abbreviated dictionary . My docstring looks as follows : The function works , but when I run py.test 's doctest , the function fails the test as it ret...
Python : accept unicode strings as regular strings in doctests
Python : I want to use different API keys for data scraping each time my program is run . For instance , I have the following 2 keys : and the following URL : When the program is run , I would like myUrl to be using apiKey1 . Once it is run again , I would then like it to use apiKey2 and so forth ... i.e : First Run : ...
Alternating between variables each run
Python : So I have created a list for multiprocessing stuff ( in particular , it is multiprocessing.Pool ( ) .starmap ( ) ) and want to reduce its memory size . The list is the following : Its memory size calculated from sys.getsizeof ( lst1_1 ) is 317840928Seeing that the type of lst1 is int32 , I thought changing the...
Reducing the memory size of a list for multiprocessing.Pool.starmap ( )
Python : I 'm making a program that , in part , rolls four dice and subtracts the lowest dice from the outcome . The code I 'm using isThat 's the best I could come up with from my so-far limited coding ability . Is there a better way to make it organize the four dice in order of size , then add together the three high...
Is there a more efficient way to organize random outcomes by size in Python ?
Python : I want to construct YYYY_WW information from dates ( where WW is a number of week ) . I am struggling with the years ' endings ( beginnings ) , where a part of a week can fall into the neighbouring year:2018_01 is obviously incorrect . Any hint for a simple workaround ? <code> import datetimeimport pandas as p...
python - Year-week combination for the end or beginning of a year
Python : I 'm trying to round a pandas DatetimeIndex ( or Timestamp ) to the nearest minute , but I 'm having a problem with Timestamps of 30 seconds - some rounding up , some rounding down ( this seems to alternate ) .Any suggestions to fix this so that 30s always rounds up ? The top result looks fine , with 57m 30s r...
Pandas Timestamp rounds 30 seconds inconsistently
Python : I have an old legacy Fortran code that is going to be called from Python.In this code , data arrays are computed by some algorithm . I have simplified it : let 's say we have 10 elements to proceed ( in the real application its more often 10e+6 than 10 ) : These arrays are then used as follows : What would be ...
What is a good way of mapping arrays in Python ?
Python : I am looking for a way in python to make a dictionary of dictionaries based on the desired structure dynamically.I have the data bellow : I give the structure I want them to be like : and finally get the data in this format : This is the manual way that I thought for achieving this : Can you think of a way to ...
Get a decision tree in a dictionary
Python : Dictionaries in python are supposed to have unique keys . Why are you allowed to do this ... Should n't this throw some sort of error ? <code> d = { ' a ' : ' b ' , ' a ' : ' c ' }
Why does python allow you to create dictionaries with duplicate keys
Python : I have a tuple of Control values and I want to find the one with a matching name . Right now I use this : Can I do it simpler than this ? Perhaps something like : <code> listViewfor control in controls : if control.name == `` ListView '' : listView = control listView = controls.FirstOrDefault ( c = > c.name ==...
Is there a way to find an item in a tuple without using a for loop in Python ?
Python : ( Sorry , could n't resist the pun ! ) I wonder why it does n't seem possible to translate : into this more readable expression , using dict comprehension : <code> dict ( [ ( str ( x ) , x ) if x % 2 else ( str ( x ) , x*10 ) for x in range ( 10 ) ] ) { str ( x ) : x if x % 2 else str ( x ) : x*10 for x in ran...
Python dict incomprehension
Python : currently I am trying to calculate optical flows of moving objects . the objects in particular are the squares that are around the circular knobs : Here is the vanilla image I am trying to process : my concern is about the right bottom-most strip . The two squares are usually unable to be detected when I have ...
OpenCV : Detect squares in dark background
Python : I am looking for a way to apply a function n items at the time along an axis . E.g.If I apply sum across the rows 2 items at a time I get : Which is the sum of 1st 2 rows and the last 2 rows.NB : I am dealing with much larger array and I have to apply the function to n items which I can be decided at runtime.T...
Apply function n items at a time along axis
Python : Is there a function in Python to get the difference between two or more values in a list ? So , in those two lists : I need to calculate the difference between every value in list1 and list2.This gives negative values , but I want the subtraction between the values of the two lists only from highest value to l...
function of difference between value
Python : Suppose I have one list which contains anagram strings . For example , And I want to construct a dictionary which contains element of that list as key and anagram strings of that element will be values of that key as a list , Also elements which will be added into list are not repeated as another key of that d...
How to add elements in list which is value of dictionary and those elements not be repeated as another keys of that dictionary ?
Python : How does Python ( 2.6.4 , specifically ) determine list membership in general ? I 've run some tests to see what it does : Which yields : This tells me that Python is probably checking the object references , which makes sense . Is there something more definitive I can look at ? <code> def main ( ) : obj = fan...
Specifics of List Membership
Python : I am trying to learn how classes work . I would like to create different classes with some shared elements and others not , but as far as I know I can create it from three different ways : Create a class with all the shared elements and then inherit this class and modify specific methods and attributes in the ...
Which strategy follow to create class ?
Python : I have a sprite which shoots bullets . Sometimes bullets also shoot out of invisible shooters.The switch from opponent to shooter mid-program works but when I want the bullets to shoot in a certain way , with delays between each shot , the bullets seem to become a single line ( the purple thing in the image is...
`` Bullets '' shot from two Pygame sprites combine into a single long line
Python : I have two three dimensional arrays , a and b , and want to find the 2D subarray of b with the elements where a had a minimum along the third axis , i.e.Is there a way I can get these values without the double loop ? I am aware of this answer : replace min value to another in numpy arraybut if I want this to w...
Find array corresponding to minimal values along an axis in another array
Python : How can I stop Python from deleting a name binding , when that name isused for binding the exception that is caught ? When did this change inbehaviour come into Python ? I am writing code to run on both Python 2 and Python 3 : Notice that exc is explicitly bound before the exception handling , so Python knows ...
Name binding in ` except ` clause deleted after the clause
Python : I came accross the following interview question and have no idea how to solve it : Given a pair , e.g cons ( 6,8 ) I am requested to return a and b separetely , e.g in this case 6 , 8 respectively.Meaning , for example , How can this be done ? <code> def cons ( a , b ) : def pair ( f ) : return f ( a , b ) ret...
How to open a closure in python ?
Python : I am trying to get all < tr class= '' **colour blue** attr1 attr2 '' > from a page . The attrs are different each time , and some of the other sibling < tr > s have colour red , colour pink etc . classes.So I 'm looking for any other characters after colour blue in class to be included in the result . I 've tr...
What 's the equivalent of '* ' for Beautifulsoup - find_all ?
Python : I have two tables that look like the followingandWhat 's the best way to take the first dataframe , lookup each parameter 's weight in the second dataframe and return a dataframe like the following ? What I was thinking was to write a function given the parameter , and value , subset table2 like the following ...
Using column header and values from one dataframe to find weights in another dataframe
Python : I have the following dfHow can I remove lowercase letters from the Name column such that when looking at data [ 'Name ' ] , I have TOM , NICK , KRISH , JACK.I tried the following but no luck , <code> data = { 'Name ' : [ 'TOMy ' , 'NICKs ' , 'KRISHqws ' , 'JACKdpo ' ] , 'Age ' : [ 20 , 21 , 19 , 18 ] } data [ ...
Removing lower case letter in column of Pandas dataframe
Python : I 'm trying to convert the values of a list using the map function but i am getting a strange result.gives : why does it not return [ ' 4 ' , '58 ' , ' 6 ' ] ? <code> s = input ( `` input some numbers : `` ) i = map ( int , s.split ( ) ) print ( i ) input some numbers : 4 58 6 < map object at 0x00000000031AE7B...
Trouble with map ( )
Python : How can I create a Python C extension wheel for MacOS that is backwards compatible ( MacOS 10.9+ ) using MacOS 10.15 ? This is what I have so far : Unfortunately , pip wheel generates a file myapp-0.0.1-cp37-cp37m-macosx_10_15_x86_64.whl , and unlike auditwheel on Linux , delocate-wheel does not modify the nam...
Create Python C extension using MacOS 10.15 ( Catalina ) that is backwards compatible ( MacOS10.9+ )
Python : Why the call to getslice does n't respect the stop I sent in , instead silently substituting 2^63 - 1 ? Does it mean that implementing __getslice__ for your own syntax will generally be unsafe with longs ? I can do whatever I need with __getitem__ anyway , I 'm just wondering why __getslice__ is apparently bro...
Slice endpoints invisibly truncated
Python : Can you please explain why this happens in Python v3.8 ? Output:2 is within the range of the small integer caching . So why are there different objects with the same value ? <code> a=round ( 2.3 ) b=round ( 2.4 ) print ( a , b ) print ( type ( a ) , type ( b ) ) print ( a is b ) print ( id ( a ) ) print ( id (...
Why does n't small integer caching seem to work with int objects from the round ( ) function in Python 3 ?
Python : I came across this expression , which I thought should evaluate to True but it doesn't.Above statement works as expected but when this : is executed , it evaluates to False.I tried searching for answers but could n't get a concrete one . Can anyone help me understand this behavior ? <code> > > s = 1 in range (...
Why does `` 1 in range ( 2 ) == True '' evaluate to False ?
Python : I have a list of lists and I want to be able to refer to the 1st , 2nd , 3rd , etc . column in a list of lists . Here is my code for the list : I want to be able to say something like : I want to know what the python syntax would be for the stuff in parenthesis . <code> matrix = [ [ 0 , 0 , 0 , 5 , 0 , 0 , 0 ,...
How to look at only the 3rd value in all lists in a list
Python : I found this kind of expression several times in a python program : It seems strange to me , and I think that it has no more sense than : Maybe I do n't know Python enough , and the expression is explained somewhere ? <code> if variable is not None : dothings ( variable ) if variable : dothings ( variable )
Does this Python expression make sense ?
Python : ProblemI have to compute many Fourier transforms . I would like to do these in parallel with my many cores . Note that I do n't want a parallel FFT algorithm , I just want to launch many embarrassingly parallel FFTs.I discover that , while my CPU usage goes up , my time to completion does not decrease.ExampleW...
Increased occupancy without speedup in FFT
Python : This sounds like an easy question , but I find it surprisingly tricky to get right with good performance.The first algorithm I 've come up with is to draw points randomly , check from a set if it 's already been drawn , and draw it otherwise . This works fine if we are drawing few points but slows down catastr...
How to efficiently draw exactly N points on screen ?
Python : I very often write code like : where I would like to write : using : Are there functor-creators like idx_f and attr_f in python , and are they of clearer when used than lambda 's ? <code> sorted ( some_dict.items ( ) , key=lambda x : x [ 1 ] ) sorted ( list_of_dicts , key=lambda x : x [ 'age ' ] ) map ( lambda...
Trivial functors
Python : I understand that the pattern r ' ( [ a-z ] + ) \1+ ' is searching for a repeated multi character pattern in the search string but I do not understand why in case k2 answer is n't 'aaaaa ' ( 5 ' a ' ) : Python 3.6.1 <code> import rek1 = re.search ( r ' ( [ a-z ] + ) \1+ ' , 'aaaa ' ) k2 = re.search ( r ' ( [ a...
Regular expressions - different string the same match
Python : What I did is obviously not something that one would want to do , rather , I was just testing out implementing __hash__ for a given class . I wanted to see if adding a phony 'hashable ' class to a dictionary , then changing it 's hash value would then result in it not being able to access it . My class looks l...
Class with changing __hash__ still works with dictionary access
Python : I have the following code : Why does this code print the text Hello instead of raise an error ? <code> with open ( True , ' w ' ) as f : f.write ( 'Hello ' )
Why does open ( True , ' w ' ) print the text like sys.stdout.write ?
Python : I have some stats in a trie which is generated periodically . I want to generate flame graphs on the difference between two tries . How do I do that ? <code> t = pygtrie.StringTrie ( separator=os.path.sep ) for dirpath , unused_dirnames , filenames in os.walk ( ROOT_DIR ) : for filename in filenames : filename...
Construct flame graph from trie
Python : I could do this in brute force , but I was hoping there was clever coding , or perhaps an existing function , or something I am not realising ... So some examples of numbers I want : The full permutation . Except with results that have ONLY six 1 's . Not more . Not less . 64 or 32 bits would be ideal . 16 bit...
How do I find all 32 bit binary numbers that have exactly six 1 and rest 0
Python : I 've inspected .__code__ objects for two functions I deemed different , but found to be identical , for a variety of expressions . If code objects are identical , as far as I understand , they compile to same bytecode , and are thus `` same '' functions.Table below is of things inserted before ; pass that mak...
Why is [ 0 ] a different function but 0 is n't ?
Python : I 'm trying to implement a basic pipelined model using Graphcore 's PopART framework ( part of the Poplar API ) to speed up my model which is split over multiple processors.I 'm following their example code , but I notice the example does not use the pipelineStage ( ) call , which is used in some of their othe...
Difference between virtualGraph and pipelineStage Graphcore 's PopART/Poplar libraries
Python : I have a list of coordinates : I have a string as follows : I want to replace intervals indicated in pairs in coordinates as start and end with character ' N'.The only way I can think of is the following : The desired output would be : where intervals , [ 1,5 ) , [ 10,15 ) and [ 25 , 35 ) are replaced with N i...
Replace a list of characters with indices in a string in python
Python : I may break the code up for readability reasons . So ... into something likeHowever , the extra awaits mean that these are not strictly equivalentAnother concurrent task can run code between print ( 'top ' ) and print ( ' 1 ' ) , so makes race conditions a touch more likely for certain algorithms.There is ( pr...
Call a coroutine without yielding the event loop
Python : Suppose I have the dict of a module ( via vars ( mod ) , or mod.__dict__ , or globals ( ) ) , e.g . : Given the dict d , how can I get back the module mod ? I.e . I want to write a function get_mod_from_dict ( d ) , which returns the module if the dict belongs to a module , or None : If get_mod_from_dict retur...
Get module instance given its vars dict
Python : How can I make sure that the variables brk1_int_c , brk1_ext_c , brk2_int_c , brk2_ext_c within the parseTwoPoleBreakres get placed into the inputList instead of the brk1_int_c , brk1_ext_c , brk2_int_c , brk2_ext_c being called outside of the function ? I 'm having difficulty with my parseTwoPoleBreakers func...
Calling Parent Variables into List
Python : Executing the script with the space after `` conv : '' the results is a `` newline '' as below : how remove \n ( new line ) ? removing the space character after conv : the script runs perfectly.results is : I 'd like have : <code> lines = lines.replace ( `` www . `` , '' conv : `` ) conv : yahoo.comconv : yaho...
remove \n after `` lines.replace ''
Python : I have a simple little decorator , that caches results from function calls in a dict as a function attribute.I now want to add the possibility to empty the cache . So I change the dynamic_programming ( ) function like this : Now let 's assume I use this little thing to implement a Fibonacci number function : B...
Reassign a function attribute makes it 'unreachable '
Python : I have a 3D dimensional array.I would like to calculate the percentile rank of a particular value along axis = 0.E.g . if the value = 4 , the output is expected to be : where the 0.25 at [ 0 ] [ 0 ] is the percentile rank of 4 in [ 0 , 6 , 12 , 18 ] , etc.If the value = 2.5 , the output is expected to be : I w...
Calculate the percentile rank of a value in a multi-dimensional array along an axis
Python : I am planning to implement C++-like constructor/destructor functionality to one of my Python classes using the handy with statement . I 've come accross this statement only for file IO up to now , but I thought it would be rather helpful for connection-based communication tasks as well , say sockets or databas...
What things to be aware of when using the with-statement for own classes ?
Python : I have 3 objects that I am populating into a JSON file format . The objects come from an API which needs rolled out to access as such : Produces output like this : My desired output : As you can see , I need each nested dictionary enclosed in a list at each level and I need to add a key/value pair at each leve...
Nested lists of dictionaries
Python : I have a .txt file with the following contents : I want to overwrite the file such that these are its new contents : Basically I want to turn the .txt file into a python dictionary so I can manipulate it . Are there built in libraries for this sort of task ? Here is my attempt : I 'm succeeding in getting the ...
Python : regex to make a python dictionary out of a sequence of words ?
Python : Working in Python3 . Say you have a million beetles , and your task is to catalogue the size of their spots . So you will make a table , where each row is a beetle and the number in the row represent the size of spots ; Also , you decide to store this in a numpy array , for which you pad the lists with None ( ...
Reasonable way to have different versions of None ?
Python : I want to merge two arrays in python in a special way . The entries with an odd index of my output array out shall be the coresponding entries of my first input array in0 . The entries with an even index in out shall be the coresponding entries of my second input array in1.in0 , in1 and out are all the same le...
Combine elements from two lists
Python : I have a column with a series of timestamps in it . Originally I thought they are in Unix timestamps system so I used the following code to convert them to date time.however , it gave me odd results so I researched a bit more and found out the timestamps are basically using the .net epoch , which is midnight 0...
Convert epoch , which is midnight 01/01/0001 , to DateTime in pandas
Python : This is my sample DataFrame . I want to apply groupby on column ' A ' , Apply rolling sum on column ' B ' based on the value of column ' C ' , means when A is 1 so window size should be 2 and instead of NaN I want the sum of remaining values regardless of window size . Currently my output is : code for above :...
How to pass dataframe column value as window size after df.groupby ?
Python : If I have a dict for exampleHowever , I do n't know how many nested items are in this dict . Instead I have a list of keys like : What is an elegant way to set d [ ' a ' ] [ ' y ' ] [ ' z ' ] [ ' 1 ' ] = 'winner ' ? Here 's what I 've tried : <code> d = { ' a ' : { `` x '' : [ ] , `` y '' : { `` z '' : { `` 1 ...
How to set `` nth '' element of a nested python dict with given list location ?
Python : I am using a Homebrew-installed Python on my Mac ( running OS X 10.13.1 ) , and of late , I ’ ve noticed that the interpreter takes a frustratingly long time to start up.In setting out to try to solve this problem , I did a simple check with time : … which revealed the egregiousness of the issue : 12 seconds !...
Python interpreter takes ~12 seconds to start up , all of which is spent in ` import pyexpat `
Python : I have a df , where the data looks like this : I want to fill in the blank cells in the Time variable according to the calendar year . So : I saw a post where pandas could be used to fill in numeric values , but since my variable is n't necessarily defined in a numeric way , I 'm not entirely sure how to apply...
How to fill in blank cells in df based on string in sequential row , Pandas
Python : Hi I have about 16 20+ gb files on a server that I need to read specific entries from , I have the code working that reads the file in the correct order if I have one of the files saved on my computer Now I need to read the files from the server without downloading each file . I was looking into paramiko and w...
iterating through a large 20+ gb file from a server with python