text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : Basically , I 'm trying to do remove any lists that begin with the same value . For example , two of the below begin with the number 1 : Because the value 1 exists at the start of two of the lists -- I need to remove both so that the new list becomes : How can I do this ? I 've tried the below , but the output...
Removing dupes in list of lists in Python
Python : I know that questions about rounding in python have been asked multiple times already , but the answers did not help me . I 'm looking for a method that is rounding a float number half up and returns a float number . The method should also accept a parameter that defines the decimal place to round to . I wrote...
Python 3.x rounding half up
Python : In Python 3.7 int ( x-1 ) == x is True for x = 5e+17Why is this so and how do I prevent this bug ? To reproduce , paste this into your Python console : ( I am using int because x is the result of a division and I need to parse it as int . ) <code> int ( 5e+17-1 ) == 5e+17 > True
Why is int ( x-1 ) == x True in Python 3.7 with some values of x ?
Python : I wanted to work on a small project to challenge my computer vision and image processing skills . I came across a project where I want to remove the hidden marks from the image . Hidden here refers to the watermarks that are not easily visible in rgb space but when you convert into hsv or some other space the ...
How to remove hidden marks from images using python opencv ?
Python : I 'm a beginning programmer in python and have a question about my code I 'm writing : When I run this program I also get 9 , 15 21 as output . But these are not prime numbers . What is wrong with my code ? Thanks ! <code> number = int ( input ( `` Enter a random number : `` ) ) for num in range ( 1 , number +...
Prime Numbers python
Python : If i run following on python2.7 console it giving me output as : While i am running same operation in python3.5.2I want to know why in python2.7.12 print statement giving me only 0.2 but in python3.5.2 print function giving me 0.19999999999999996 . <code> > > > 1.2 - 1.00.19999999999999996 > > > print 1.2 - 1....
Why does the print function in Python3 round a decimal number ?
Python : I ’ m working with sympy on a symbolic jacobian matrix J of size QxQ . Each coefficient of this matrix contains Q symbols , from f [ 0 ] to f [ Q-1 ] . What I ’ d like to do is to substitute every symbol in every coefficient of J with known values g [ 0 ] to g [ Q-1 ] ( which are no more symbols ) . The fastes...
Slow substitution of symbolic matrix with sympy
Python : I 'm getting a really weird problem with P4Python since I started implementing workspace awareness.The situation is as follows : I have a `` P4Commands '' module which inherits P4 and connects in the __init__ ( ) Then , I have respectively the following classes : P4UserP4WorkspaceP4ChangelistThe P4Commands mod...
File ( s ) not on client
Python : I 'm using Django and Neo4j together with neomodel as the OGM ( ORM for graphs ) . It 's working nicely but when it comes to testing , Neomodel does n't support the usual Django behavior with the relational databases . I mean that it does n't create a temporal Neo4j instance that is created at the beginning of...
Neo4j and Django testing
Python : I would like to scrape a table from the Ligue 1 football website . Specifically the table which contains information on cards and referees . http : //www.ligue1.com/LFPStats/stats_arbitre ? competition=D1I am using the following code : This returns another table somewhere else in the html . I have tried to cir...
Ca n't Scrape a Specific Table using BeautifulSoup4 ( Python 3 )
Python : In numpy , I have an array that can be either 2-D or 3-D , and I would like to reduce it to 2-D while squaring each element . So I tried this and it does n't work : It returns this error : I suppose einsum does n't assume that when the ellipsis goes away in the right hand side , I want to sum over the ellipsis...
Summing over ellipsis broadcast dimension in numpy.einsum
Python : Consider we 've got a bunch of subtress that look like this : I 'm trying to figure how to code a merge function such as doing something like this : will produce : but doing something like this : would produce : Said otherwise , loading the subtrees in the same order will always produce the same tree but if yo...
How to create a tree from a list of subtrees ?
Python : After reading this question , I noticed that S. Lott might have liked to use an “ ordered defaultdict ” , but it does n't exist . Now , I wonder : Why do we have so many dict classes in Python ? dictblist.sorteddictcollections.OrderedDictcollections.defaultdictweakref.WeakKeyDictionaryweakref.WeakValueDictiona...
Why are n't Python dicts unified ?
Python : Is it possible to test methods inside interactive python and retain blank lines within them ? This gives the familiar errorSo , yes a workaround is to remove all blank lines inside functions . I 'd like to know if that were truly mandatory to be able to run in interactive mode/REPL.thanks <code> def f1 ( ) : i...
How to configure interactive python to allow blank lines inside methods
Python : Assume I have the following DataFrameI need to return a second DataFrame that lists the number of occurrences of A and B by day . i.e.I have a feeling this involves `` groupby '' , but I dont know enough about it to get it into the format above ^ <code> dic = { `` Date '' : [ `` 04-Jan-16 '' , `` 04-Jan-16 '' ...
Pandas : return number of occurrences by date
Python : I understand that given an iterable such asI can turn it into a list and slice off the ends at arbitrary points with , for exampleor reverse it withor combine the two withHowever , trying to accomplish this in a single operation produces in some results that puzzle me : Only after much trial and error , do I g...
Mysterious interaction between Python 's slice bounds and `` stride ''
Python : I 've been playing around with Cython in preparation for other work . I tried a simple test case and noticed something odd with the way my code performs for larger problem sizes . I created a simple min/max function that calculates the min and max of a 2D float32 array and compared it to running numpy.min ( a ...
Cython vs numpy performance scaling
Python : I recently made the switch from python 2 to python 3 . Python 3 documentation reads : `` Removed reload ( ) . Use imp.reload ( ) '' It does n't really say why though.This question describes how it 's done now in python 3 . Does anyone have any idea why it 's been removed from the built-ins and now requires imp...
Why was reload removed from python builtins in the switch to python3 ?
Python : PrefaceI have a test where I 'm working with nested iterables ( by nested iterable I mean iterable with only iterables as elements ) . As a test cascade considerE.g . foo may be simple identity functionand contract is simply checks that flattened iterables have same elementsBut if some of nested_iterable eleme...
deep copy nested iterable ( or improved itertools.tee for iterable of iterables )
Python : Let 's say I want to open a text file for reading using the following syntax : But if I detect that it ends with .gz , I would call gzip.open ( ) . If `` do something '' part is long and not convenient to write in a function ( e.g . it would create a nested function , which can not be serialized ) , what is th...
python : `` with '' syntax for opening files with two functions
Python : I 'm doing a bit more complex operation on a dataframe where I compare two rows which can be anywhere in the frame.Here 's an example : Now what I am doing here is that I have pairings of strings in A and B , for example a_c which I call AB . And I have the reverse pairing c_a as well . I sum over the numbers ...
Pandas : Get the only value of a series or nan if it does not exist
Python : my very first day with Python.I like to filter on a trace file generated by C.Each double from C is formatted in the file bytwo hex strings representing 32 bit of the 64 double.e.g . 1234567890.3 ( C double ) inside file : How can I parse and combine it to further work with a Python float ? Thanks in advance <...
Converting from a C double transferred in two hex strings
Python : I am using datetime in some Python udfs that I use in my pig script . So far so good . I use pig 12.0 on Cloudera 5.5However , I also need to use the pytz or dateutil packages as well and they dont seem to be part of a vanilla python install . Can I use them in my Pig udfs in some ways ? If so , how ? I think ...
Pig : is it possible to use pytz or dateutils for Python udfs ?
Python : I tried it on virtualenv : <code> ( venv ) $ pip install Django==1.0.4Downloading/unpacking Django==1.0.4 Could not find a version that satisfies the requirement Django==1.0.4 ( from versions : ) No distributions matching the version for Django==1.0.4Storing complete log in /home/tokibito/.pip/pip.log
Why is Django 1.0.x not able to install from PyPI ?
Python : BackgroundThe Python 3 documentation clearly describes how the metaclass of a class is determined : if no bases and no explicit metaclass are given , then type ( ) is used if an explicit metaclass is given and it is not an instance of type ( ) , then it is used directly as the metaclass if an instance of type ...
Why does the class definition 's metaclass keyword argument accept a callable ?
Python : I want to enforce that all items in a list are of type x . What would be the best way to do this ? Currently I am doing an assert like the following : Where int is the type I 'm trying to enforce here . Is there a better way to do this ? <code> a = [ 1,2,3,4,5 ] assert len ( a ) == len ( [ i for i in a if isin...
How to check to make sure all items in a list are of a certain type
Python : This dictionary corresponds with numbered nodes : Using two print statements , I want to print marked and unmarked nodes as follows : Marked nodes : 0 1 2 6 7Unmarked nodes : 3 4 5 8 9I want something close to : <code> { 0 : True , 1 : True , 2 : True , 3 : False , 4 : False , 5 : False , 6 : True , 7 : True ,...
How to print with inline if statement ?
Python : There is a puzzle which I am writing code to solve that goes as follows.Consider a binary vector of length n that is initially all zeros . You choose a bit of the vector and set it to 1 . Now a process starts that sets the bit that is the greatest distance from any 1 bit to $ 1 $ ( or an arbitrary choice of fu...
Fast way to place bits for puzzle
Python : I have text in my database . I send some text from xhr to my view . Function find does not find some unicode chars.I want to find selected text using : but sometimes variable 'selection ' contains a char like that : whereas in variable 'text ' there was : They are just different forms of the same thing . How t...
Python the same char not equals
Python : I 'm playing around with generators and generator expressions and I 'm not completely sure that I understand how they work ( some reference material ) : So it looks like generator.send was ignored . That makes sense ( I guess ) because there is no explicit yield expression to catch the sent information ... How...
Attempting to understand yield as an expression
Python : I am trying to do the following with a sed script but it 's taking too much time . Looks like something I 'm doing wrongly.Scenario : I 've student records ( > 1 million ) in students.txt.In This file ( each line ) 1st 10 characters are student ID and next 10 characters are contact number and so onstudents.txt...
SED or AWK script to replace multiple text
Python : For a data analysis task , I want to find zero crossings in a numpy array , coming from a convolution with first a sobel-like kernel , and then a mexican hat kernel . Zero crossings allow me to detect edges in the data.Unfortunately , the data is somewhat noisy and I only want to find zero crossings with a min...
Finding minimal jump zero crossings in numpy
Python : Is there a method to print terminal formatted output to a variable ? I want that string ' b ' to a variable - so how to do it ? I am working with a text string from telnet . Thus I want to work with the string that would be printed to screen.So what I am looking for is something like this : Another example wit...
How to print terminal formatted output to a variable
Python : Guided by this answer I started to build up pipe for processing columns of dataframe based on its dtype . But after getting some unexpected output and some debugging i ended up with test dataframe and test dtype checking : OUTPUT : Almost everything is good , but this test code produces two questions : The mos...
Caveats while checking dtype in pandas DataFrame
Python : Why is the code below termed 'age-old disapproved method ' of printing in the comment by 'Snakes and Coffee ' to Blender 's post of Print multiple arguments in python ? Does it have to do with the backend code/implementation of Python 2 or Python 3 ? <code> print ( `` Total score for `` + str ( name ) + `` is ...
Why is print ( `` text '' + str ( var1 ) + `` more text '' + str ( var2 ) ) described as `` disapproved '' ?
Python : Consider the following simple example class , which has a property that exposes a modified version of some internal data when called : The value.setter works fine for regular assignment , but of course breaks down for compound assignment : The desired behavior is that x.value += 5 should be equivalent to x.val...
Property setters for compound assignment ?
Python : I have the following code : However , when I run python ./pypy/pypy/translator/goal/translate.py t.py I get the following error : There was actually more to the error but I thought only this last part was relevant . If you think more of it might be helpful , please comment and I will edit.In fact , I get anoth...
RPython sys methods do n't work
Python : I 'm writing a passion program that will determine the best poker hand given hole cards and community cards . As an ace can go both ways in a straight , I 've coded this as [ 1 , 14 ] for a given 5 card combination.I understand recursion but implementing it is a different story for me . I 'm looking for a func...
Split list recursively until flat
Python : I have a log file that is formatted in the following way : I am attempting to run some stats over this dataset . I have the following code : I did not want to define a class for such a simple dataset , so I used a name tuple . When I attempt to run , I get this error : It appears that the lambda function is op...
`` reduce '' function in python not work on `` namedtuple '' ?
Python : When creating a BrowserView in Plone , I know that I may optionally configure a template with ZCML like so : Or alternatively in code : Is there any difference between the two approaches ? They both appear to yield the same result.Sub-question : I know there is a BrowserView class one can import , but conventi...
What is the difference between template in ZCML and ViewPageTemplateFile
Python : Consider : I want to replace matches randomly with entries of a list repl . But when using lambda m : random.choice ( repl ) as a callback , it does n't replace \1 , \2 etc . with its captures any more , returning `` \1bla\2 '' as plain text.I 've tried to look up re.py on how they do it internally , so I migh...
How can I pass a callback to re.sub , but still inserting match captures ?
Python : I have a web application with an associated API and database . I 'd like to use the same Django models in the API , but have it served separately by different processes so I can scale it independently . I also do n't need the API to serve static assets , or any of the other views . The complication is that the...
django deploying separate web & api endpoints on heroku
Python : Is it possible to create hyperlinks without leading and trailing spaces ? The following does n't work : The reason I 'm asking is I 'm working with Chinese text . Spaces are not used as word delimiters in Chinese . With the added spaces the text does n't look well formatted , for example : 没有空格就对了。versus 多了 空格...
RestructuredText - Hyperlinks without leading and trailing spaces
Python : I have a Python script that interfaces with an API . The script is started from a PHP page . I wrote both scripts , so I can change the code in either as appropriate.The Python script needs a username and password to interface with the API . My first inclination is to pass them to Python as CLI arguments : How...
Start process , hide arguments from ps
Python : I 'm trying to pack and send columnar data over a socket connection . To speed it up , I thought about splitting the packing ( struct.pack ) to multiple processes . To avoid pickling both ways , I thought it might be better to have the packing processes send the data themselves , as it was said socket objects ...
Sending over the same socket with multiprocessing.pool.map
Python : Perhaps I am doing something wrong while z-normalizing my array . Can someone take a look at this and suggest what 's going on ? In R : In Python using numpy : Am I using numpy incorrectly ? <code> > data < - c ( 2.02 , 2.33 , 2.99 , 6.85 , 9.20 , 8.80 , 7.50 , 6.00 , 5.85 , 3.85 , 4.85 , 3.85 , 2.22 , 1.45 , ...
Output values differ between R and Python ?
Python : I see from here that I can pick out tests based on their mark like so : Let 's say I have a test decorated like so : I 'd like to do something like the following : That way I run test_Foo with the parameter of 'release ' but not the parameter of 'debug ' . Is there a way to do this ? I think I can do this by w...
Pytest select tests based on mark.parameterize value ?
Python : I 'm running a Debian 10 stable x64 system with the dwm window manager , and I 'm using Python 3.7.3 . From what I can tell from some example code and the draw_text method itself , I should be able to draw text on the root window with code like this : This code runs without error , but no text is displayed . I...
How do I write text to the root window using Python 's Xlib ?
Python : I wish to be able to perform python debugging using print ( ) or similar method where it prints the passed expression in addition to the usual output.For instance , for the following code : Current Output : Expected Output : Currently , the same can be achieved by manually adding the expression string , ( not ...
print ( ) method to print passed expression literally along with computed output for quick debugging
Python : I 'm looking at an open source package ( MoviePy ) which adapts its functionality based on what packages are installed . For example , to resize an image , it will use the functionality provided by OpenCV , else PIL/pillow , else SciPy . If none are available , it will gracefully fallback to not support resizi...
Can I use Environment Markers in tests_require in setup.py ?
Python : HighLine is a Ruby library for easing console input and output . It provides methods that lets you request input and validate it . Is there something that provides functionality similar to it in Python ? To show what HighLine does see the following example : It asks `` Yes or no ? `` and lets the user input so...
Is there a Python equivalent to HighLine ?
Python : I want to replace those elements of list1 whose indices are stored in list indices by list2 elements . Following is the current code : Is it possible to write a one-liner for the above four lines using lambda function or list comprehension ? EDITlist1 contains float valueslist2 contains float valuesindices con...
Python one liner to substitute a list indices
Python : How can I easily create an object that can not be pickled for testing edge cases in my rpc code ? It needs to be : SimpleReliable ( not expected to break in future versions of python or pickle ) Cross platformEdit : The intended use looks something like this : <code> class TestRPCServer : def foo ( self ) : re...
Create object that can not be pickled
Python : I 've recently stumbled over this expression : It evaluates to False , but I do n't understand why.True == False is False and False in ( False , ) is True , so both ( to me ) plausible possibilitiesandevaluate to True , as I would have expected.What is going wrong here ? <code> True == False in ( False , ) Tru...
How does operator binding work in this Python example ?
Python : Recently , reading Python `` Functional Programming HOWTO '' , I came across a mentioned there test_generators.py standard module , where I found the following generator : It took me a while to understand how it works . It uses a mutable list values to store the yielded results of the iterators , and the N+1 i...
Conjoin function made in functional style
Python : As title , I creates the zip file from my Django backend server ( hosted on a Ubuntu 14.04.1 LTS ) using the python zipfile module : I managed to open it using my Mac in Finder , but no success using the SSZipArchive library . I have tried using the latest commit of master branch and also tag v1.0.1 and v0.4.0...
Unable to unzip a large zip file ( 3.3GB ) in iOS9 using SSZipArchive
Python : When I train a SVC with cross validation , cross_val_predict returns one class prediction for each element in X , so that y_pred.shape = ( 1000 , ) when m=1000.This makes sense , since cv=5 and therefore the SVC was trained and validated 5 times on different parts of X . In each of the five validations , predi...
Why is cross_val_predict not appropriate for measuring the generalisation error ?
Python : Is there a built-in function that works like zip ( ) , but fills the results so that the length of the resulting list is the length of the longest input and fills the list from the left with e.g . None ? There is already an answer using zip_longest from itertools module and the corresponding question is very s...
zip ( ) -like built-in function filling unequal lengths from left with None value
Python : I 'm running Spark Streaming with two different windows ( on window for training a model with SKLearn and the other for predicting values based on that model ) and I 'm wondering how I can avoid one window ( the `` slow '' training window ) to train a model , without `` blocking '' the `` fast '' prediction wi...
How to avoid one Spark Streaming window blocking another window with both running some native Python code
Python : Let 's say I want to create a list of ints using Python that consists of the cubes of the numbers 1 through 10 only if the cube is evenly divisible by four.I wrote this working line : My beef with this line of code is that it 's computing the cube of x twice . Is there more pythonic way to write this line ? Or...
Is this list comprehension pythonic enough ?
Python : I am looking for a regex pattern that will match third , fourth , ... occurrence of each character . Look below for clarification : For example I have the following string : I want to replace all the duplicated characters after the second occurrence . The output will be : Some regex patterns that I tried so fa...
Match and remove duplicated characters : Replace multiple ( 3+ ) non-consecutive occurrences
Python : I am using Django purely for creating template ( no server ) .Here is the scheme I have : page1.htmlbase.htmlcode_to_make_template.pyThe directory structure looks like this : But when I run code_to_make_template.py I got this message : What 's the right way to do it ? <code> { % extends `` base.html '' % } { %...
How to use Django templating as is without server
Python : Here 's some data from another question : What I would do first is to add quotes across all words , and then : Is there a smarter way to do this ? <code> positive negative neutral1 [ marvel , moral , bold , destiny ] [ ] [ view , should ] 2 [ beautiful ] [ complicated , need ] [ ] 3 [ celebrate ] [ crippling ,...
How do you read in a dataframe with lists using pd.read_clipboard ?
Python : I strace 'd a simple script using perl and bash.Why does perl need the pseudorandom number generator for such a trivial script ? I would expect opening /dev/urandom only after the first use of random data.Edit : I also tested python and rubyWhy do perl and ruby open it with different modes ? <code> $ strace pe...
why do perl , ruby use /dev/urandom
Python : I have a list of dictionaries , and I need to get a list of the values from a given key from the dictionary ( all the dictionaries have those same key ) .For example , I have : I need to get 1 , 2 , 3.Of course , I can get it with : But I would like to get a nicer way to do so . <code> l = [ { `` key '' : 1 , ...
Get a list of values from a list of dictionaries ?
Python : I know how to detect if my Python script 's stdout is being redirected ( > ) using sys.stdout.isatty ( ) but is there a way to discover what it 's being redirected to ? For example : Is there a way to discover the name somefile.txt on both Windows and Linux ? <code> python my.py > somefile.txt
Is there a way to find out the name of the file stdout is redirected to in Python
Python : I have a dataset with ~300 points and 32 distinct labels and I want to evaluate a LinearSVR model by plotting its learning curve using grid search and LabelKFold validation.The code I have looks like this : My question is how to setup the cv attribute for the grid search and learning curve so that it will brea...
How to nest LabelKFold ?
Python : Python 's print statement normally seems to print the repr ( ) of its input . Tuples do n't appear to be an exception : But then I stumbled across some strange behavior while messing around with CPython 's internals . In short : if you trick Python 2 into creating a self-referencing tuple , printing it directl...
What method does Python 2 use to print tuples ?
Python : The following code : produces for numpy 1.13.3However , if I change the 127 to a 126 , both return a np.int8 array . And if I change the 127 to a 128 both return a np.int16 array.Questions : Is this expected behaviour ? Why is it different for the two platforms for this one case ? <code> > > > import numpy as ...
Multiplying a np.int8 array with 127 yields different numpy array types depending on platform
Python : My goal is to have one cell in Jupyter notebook displaying multiple interactive widgets . Specifically , I would like to have four slider for cropping an image and then another separate slider for rotating this cropped image . Of course , both plots should be displayed when I run the code . Here is what I have...
How to include multiple interactive widgets in the same cell in Jupyter notebook
Python : I am writing a python wrapper to the Microsoft Dynamics Business Connector .net assembly.This is my code : This is my errors when running pytest : .net decompiler shows : P.S . The stackoverflow grader asks me to add more details : ) What else - obj = clr.AddRefrence works and I can see a Microsoft attribute i...
Wrapping Microsoft Dynamics Business Connector .net assembly in python
Python : I try to access the classmethod of a parent from within __init_subclass__ however that does n't seem to work.Suppose the following example code : which produces the following exception : The cls.__mro__ however shows that Foo is a part of it : ( < class '__main__.Bar ' > , < class '__main__.Foo ' > , < class '...
Using ` super ( ) ` within ` __init_subclass__ ` does n't find parent 's classmethod
Python : I was a happy man , having his own happy local pip index . One day I 've updated pip client and I 'm not happy anymore : But WHY ? I have SSL enabled on my server and my pip.conf file looks like this : How is 'secure and verifiable'/'insecure and unverifiable ' file defined ? How PIP distinguishes between them...
In python PIP , how can I make files in my private pip index `` secure and verifiable '' ?
Python : I have the following dataframe : I need to be able to keep track of when the latest maximum and minimum value occurred within a specific rolling window . For example if I were to use a rolling window period of 5 , then I would need an output like the following : All this shows is , what is the date of the late...
Most recent max/min value
Python : I 've been boggling my head to make this array for some time but having no success doing it in a vectorized way.I need a function that takes in the 2d array size n and produces a 2d array of size ( n , n ) looking like this : ( and can take odd number arguments ) Any suggestions would be much appreciated , tha...
Build 2d pyramidal array - Python / NumPy
Python : I 'm generating some pdfs using ReportLab in Django . I followed and experimented with the answer given to this question , and realised that the double-quotes therein do n't make sense : gives filename constant_-foo_bar-.pdfgives filename constant_foo_bar.pdfWhy is this ? Is it just to do with slug-esque sanit...
why are python double-quotes converted to hyphen in filename ?
Python : Hi I get a strange error message : Property user is corrupt in the datastoreCan you tell me what it means and what I should do ? Here 's the full traceEDIT : Here is my entire model . I 've not changed it for several deployments : EDIT 2 : By changing the variable PAGESIZE I can make the page load for the most...
Property user is corrupt in the datastore :
Python : I was searching for an algorithm to generate prime numbers . I found the following one done by Robert William Hanks . It is very efficient and better than the other algorithms but I can not understand the math behind it.What is the relation between the array of Trues values and the final prime numbers array ? ...
Prime numbers generator explanation ?
Python : I know we can overload behavior of instances of a class , e.g . - We can change the result of print s : Can we change the result of print Sample ? <code> class Sample ( object ) : passs = Sample ( ) print s < __main__.Sample object at 0x026277D0 > print Sample < class '__main__.Sample ' > class Sample ( object...
Can we overload behavior of class object
Python : I 've written a script in python to reach the target page where each category has their avaiable item names in a website . My below script can get the product names from most of the links ( generated through roving category links and then subcategory links ) .The script can parse sub-category links revealed up...
Trouble parsing product names out of some links with different depth
Python : Let 's say you work with a wrapper object : This object implements __iter__ , because it passes any call to it to its member f , which implements it . Case in point : According to the documentation ( https : //docs.python.org/3/library/stdtypes.html # iterator-types ) , IterOrNotIter should thus be iterable.Ho...
How come an object that implements __iter__ is not recognized as iterable ?
Python : Inspired by this earlier stack overflow question I have been considering how to randomly interleave iterables in python while preserving the order of elements within each iterable . For example : The original question asked to randomly interleave two lists , a and b , and the accepted solution was : However , ...
Interleaving multiple iterables randomly while preserving their order in python
Python : I have a large array with 1024 entries that have 7 bit values in range ( 14 , 86 ) This means there are multiple range of indices that have the same value.For example , I want to feed this map to a python program that would spew out the following : Some code to groupby mapped value is ready but I am having dif...
Compressing a sinewave table
Python : This question is a follow up to my answer in Efficient way to compute the Vandermonde matrix.Here 's the setup : Now , I 'll compute the Vandermonde matrix in two different ways : And , Sanity check : These methods are identical , but their performance is not : So , the first method , despite requiring a trans...
Broadcasted NumPy arithmetic - why is one method so much more performant ?
Python : In Python 3I have n't considered corner cases ( exponent < = 0 ) Why do n't we use the above-written code in-place of code computed using Divide and Conquer Technique , this code looks more simple and easy to understand ? Is this code less efficient by any means ? <code> def power ( base , exponent ) : if expo...
Finding Power Using Recursion
Python : This is a follow up to this answer to my previous question Fastest approach to read thousands of images into one big numpy array.In chapter 2.3 `` Memory allocation of the ndarray '' , Travis Oliphant writes the following regarding how indexes are accessed in memory for C-ordered numpy arrays . ... to move thr...
The accessing time of a numpy array is impacted much more by the last index compared to the second last
Python : I want to maintain a Django model with a unique id for every combination of choices within the model . I would then like to be able to update the model with a new field and not have the previous unique id 's change . The id 's can be a hash or integer or anything.What 's the best way to achieve this ? Given th...
Using the Django ORM , How can you create a unique hash for all possible combinations
Python : I 've been working on an R package which interfaces with Python via a simple server script and socket connections . I can test in on my own machine just fine , but I 'd like to test it on a Travis build as well ( I do n't want to go through the effort of setting up a Linux VM ) . To do this I would need a Pyth...
Installing both Python and R for a Travis build ?
Python : I need to write a function that accepts a list of lists representing friends for each person and need to convert it into a dictionary . so an input of [ [ ' A ' , ' B ' ] , [ ' A ' , ' C ' ] , [ ' A ' , 'D ' ] , [ ' B ' , ' A ' ] , [ ' C ' , ' B ' ] , [ ' C ' , 'D ' ] , [ 'D ' , ' B ' ] , [ ' E ' ] ] should re...
Converting list of lists to a dictionary with multiple values for a key
Python : I was looking at this and this threads , and though my question is not so different , it has a few differences . I have a dataframe full of floats , that I want to replace by strings . Say : To this table I want to replace by several criteria , but only the first replacement works : If I instead do the selecti...
Pandas : Selecting and modifying dataframe based on even more complex criteria
Python : Above , I create a dict with a hash collision , and two slots occupied . How is that getitem handled for the integer 1 ? And how does the indexing manage to resolve the correct value for a complex literal indexing ? Python 2.7.12 / Linux . <code> > > > one_decimal = Decimal ( ' 1 ' ) > > > one_complex = comple...
Putting two keys with the same hash into a dict
Python : Psychology experiments often require you to pseudo-randomize the trial order , so that the trials are apparently random , but you do n't get too many similar trials consecutively ( which could happen with a purely random ordering ) . Let 's say that the visual display on each trial has a colour and a size : An...
Sorting algorithm to keep equal values separated
Python : I have some kind of verbose logic that I 'd like to compact down with some comprehensions.Essentially , I have a dict object that I 'm reading from which has 16 values in it that I 'm concerned with . I 'm getting the keys that I want with the following comprehension : The source dictionary kind of looks like ...
Combined list and dict comprehension
Python : I 'm trying to make a basic Skype bot using Skype4Py and have encountered a rather serious error . I am working on a 64 bit windows 7 with the 32bit Python 2.7.8. installed , along with the latest version of Skype4Py.My main demand is that the bot has an overview of 5 different Skype chats : four individual ch...
Skype4Py MessageStatus not firing consistently
Python : In a current benchmark about mongodb drivers , we have noticed a huge difference in performance between python and .Net ( core or framework ) .And the a part of the difference can be explained by this in my opinion.We obtained the following results : We took a look to the memory allocation in C # and we notice...
How to reach the same performance with the C # mongo driver than PyMongo in python ?
Python : Given a function f ( ) , a number x and an integer N , I want to compute the List : An obvious way to do this in Python is the following Python code : But I want to know if there is a better or faster , way to do this . <code> y = [ x , f ( x ) , f ( f ( x ) ) , ... , f ( f ... M times ... f ( f ( x ) ) ] y = ...
Iterated function in Python
Python : I have a script that consumes command line arguments and I would like to implement two argument-passing schemes , namely : Typing the arguments out at the command line.Storing the argument list in a file , and passing the name of this file to the program via the command line.To that end I am passing the argume...
How can I pass command line arguments contained in a file and retain the name of that file ?
Python : Before Python-3.3 , I detected that a module was loaded by a custom loader with hasattr ( mod , '__loader__ ' ) .After Python-3.3 , all modules have the __loader__ attribute regardless of being loaded by a custom loader.Python-2.7 , 3.2 : Python-3.3 : How do I detect that a module was loaded by a custom loader...
Python - How do you detect that a module has been loaded by custom loader ?
Python : Python has a nice feature that gives the contents of an object , like all of it 's methods and existing variables , called dir ( ) . However when dir is called in a function it only looks at the scope of the function . So then calling dir ( ) in a function has a different value than calling it outside of one ....
dir inside function
Python : I have the following custom class : This class does exactly what i want for when i have multiple keys , but does n't do what i want for single keys.Let me demonstrate what my code outputs : But then : I want it to be : Here was my attempt to fix it to act the way i want ( which led to infinite recursion ) : <c...
Custom OrderedDict that returns itself