text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : I want to perform a specific operation . Namely , from a matrix : To the followingOr in words : multiply every entry by the identity matrix and keep the same order.Now I have accomplished this by using numpy , using the following code . Here N and M are the dimensions of the starting matrix , and the dimension... | Modifying ( keras/tensorflow ) Tensors using numpy methods |
Python : I 'm trying to use my local s3ninja with s3cmd.Every command like : s3cmd ls s3 : //test throws the same exceptions.The s3cfg seems to be ok and the called endpoints are correct.Was anyone able to use s3ninja with s3cmd ? PS : I know S3 is n't costly and there are many better ways to test against S3 . I need S... | S3Cmd does n't work with S3 Ninja |
Python : I need to transform some text files into HTML code . I 'm stuck in transforming a list into an HTML unordered list . Example source : some text in the document * item 1 * item 2 * item 3 some other textThe output should be : Currently , I have this : which creates an HTML list without < ul > tags.How can I ide... | Python Regex - Identifying the first and last items in a list |
Python : In Python , if I want to get the first n characters of a string minus the last character , I do : What 's the Ruby equivalent ? <code> output = 'stackoverflow'print output [ : -1 ] | What 's the Ruby equivalent of Python 's output [ : -1 ] ? |
Python : I 'm trying to figure out how to setup Test Driven Development for GAE.I start the tests with : I keep getting the error : The datastore does n't exist until I create it in the setUp ( ) , but I 'm still getting an error that the entities already exists ? I 'm using the code from the GAE tutorial . Here is my ... | How am I getting 'InternalError : table `` dev~guestbook ! ! Entities '' already exists ' when I just created datastore ? |
Python : Let 's say I have the following code : This generates the following list : Then I want to modify the first element in the first list : I expected only the first element of the list to be modified , but actually the first element of each list was changed : I managed to find another way to represent my data to a... | Python list confusion |
Python : Assume the following code structure : I run python inside 1/ and do import hhh.foo.baz . It fails : Now I replace baz.py with : and again do import hhh.foo.baz . Now it works , although I ’ m loading the same module , only binding a different name.Does this mean that the distinction between import module and f... | Why do these two Python imports work differently ? |
Python : I got some working code using einsum function . But as einsum is currently still like black voodoo for me . I was wondering , what this code actually is doing and if it can be somehow optimized using np.dotMy data looks likes thisAnd my existing functions einsum functions looks like thisBut what does it really... | Black voodoo of NumPy Einsum |
Python : For example , I am now learning wxPython , specifically a class ' init function : As a matter of good programming practice , should I memorize the order of the parameters , or just the keywords and call the function using the keywords everytime ? Is it better to do the latter for readability ? <code> __init__ ... | Should I memorize the order of function arguments when learning a new module ? |
Python : I 'm new to tensorflow . I have the following problem : input : list of floats ( or a dynamic array . In python list is the datatype to be used ) Output : is a 2-d array of size len ( input ) × len ( input ) Example1 : Input : Output : I tried to create the function using while loop and calculating each row in... | Tensorflow : Regarding tensorflow functions |
Python : This is not homework.I saw this article praising Linq library and how great it is for doing combinatorics stuff , and I thought to myself : Python can do it in a more readable fashion.After half hour of dabbing with Python I failed . Please finish where I left off . Also , do it in the most Pythonic and effici... | Help me finish this Python 3.x self-challenge |
Python : I have a Python utility that goes over a tar.xz file and processes each of the individual files . This is a 15MB compressed file , with 740MB of uncompressed data.On one specific server with very limited memory , the program crashes because it runs out of memory . I used objgraph to see which objects are creat... | Leaking TarInfo objects |
Python : I have a list with points ( centroids ) and some of them have to be removed.How can I do this without loops ? I 've tried the answer given here but this error is shown : My lists look like this : And I want to remove the elements in index . The final result would be : <code> list indices must be integers , not... | Remove list of indices from a list in Python |
Python : the file contains 2000000 rows : each row contains 208 columns , separated by comma , like this : The program read this file to a numpy narray , I expected it will consume about ( 2000000 * 208 * 8B ) = 3.2GB memory . However , when the program read this file , I found the program consumes about 20GB memory . ... | why numpy narray read from file consumes so much memory ? |
Python : I suddenly ca n't load newly upgraded modules modules , e.g scikit-learn , zope , but I can find other packages . Even though the path links from the import points to the correct anaconda folder , which contains all the code . Any ideas what might be wrong and how to fix it ? <code> Python 2.7.13 |Anaconda cus... | Suddenly I ca n't load some newly upgraded modules in Python |
Python : I 'm running Python 2.5 ( r25:51908 , Sep 19 2006 , 09:52:17 ) [ MSC v.1310 32 bit ( Intel ) ] on win 32When I 'm asking PythonThat 's fine . When I askThat 's fine , too . But when I ask So according Python `` u11-Phrase 100.wav '' comes before `` u11-Phrase 1000.wav '' but `` u11-Phrase 101.wav '' comes afte... | Python sorts `` u11-Phrase 1000.wav '' before `` u11-Phrase 101.wav '' ; how can I overcome this ? |
Python : I have a small project I want to try porting to Python 3 - how do I go about this ? I have made made the code run without warnings using python2.6 -3 ( mostly removing .has_key ( ) calls ) , but I am not sure of the best way to use the 2to3 tool . Use the 2to3 tool to convert this source code to 3.0 syntax . D... | Python 3 porting workflow ? |
Python : Is the following code for generating primes pythonic ? Note that next ( next_p ) will eventually throw a StopIteration error which somehow ends the function get_primes . Is that bad ? Also note that next_p is a generator which iterates over primes , however primes changes during iteration . Is that bad style ?... | is this primes generator pythonic |
Python : So I 've trying to model a small user-group relationship in Neo4j with Django . I am currently employing the Neo4django python package seen here . Now , I have nodes representing my users , and nodes representing my groups , and relationships that link them indicating membership . What I 'm hoping to also do i... | Neo4django Relationship properties |
Python : I 'm wondering if anyone has a sort of hacky / cool solution to this problem . I have a text file like so : So I have some blocks that all contain lines that can be split into a dict , and some that can not . How can I take lines without the : character and join them to the previous line ? Here 's what I 'm cu... | Python iterate over list and join lines without a special character to the previous item |
Python : I 'm currently trying to implement a siamese-net in Keras where I have to implement the following loss function : detailed description of loss function from paperWhere KL is the Kullback-Leibler divergence and HL is the Hinge-loss.During training , I label same-speaker pairs as 1 , different speakers as 0 . Th... | Custom combined hinge/kb-divergence loss function in siamese-net fails to generate meaningful speaker-embeddings |
Python : I would like to match strings , using Pythons regex module.In my case I want to verify that strings start , end and consist of upper case letters combined by `` _ '' . As an example , the following string is valid : `` MY_HERO2 '' . The following strings are not valid : `` _MY_HREO2 '' , `` MY HERO2 '' , `` MY... | Python regex slow when whitespace in string |
Python : I am trying to read one short and long from a binary file using python struct . But the which is wrong , It should have been 2 bytes for short and 8 bytes for long . I am not sure i am using the struct module the wrong way . When i print the value for each it is Is there a way to force python to maintain the p... | Python struct calsize different from actual |
Python : I 've been using the sys.settrace function to write a tracer for my program , which is working great except that it does n't seem to get called for built-in functions , like open ( 'filename.txt ' ) . This behavior does n't seem to be documented , so I 'm not sure if I 'm doing something wrong or if this is th... | python 's sys.settrace wo n't trace builtin functions |
Python : I have the following code in C++ : I wrapped it in boost : :python in this way : When I try to call person.GetGender ( ) from Python I get the following exception : How can I tell the GetGender function what type to return explicitly ? <code> class Person { public : enum Gender { Male , Female } ; Gender GetGe... | Namespaces mixed up when returning scoped enum from class method |
Python : My task is to reproduce the plot below : It comes from this journal ( pg 137-145 ) In this article , the authors describe a kleptographic attack called SETUP against Diffie-Hellman keys exchange . In particular , they write this algorithm : Now , in 2 the authors thought `` Maybe we can implement honest DHKE a... | Implementation of kleptography in Python ( SETUP attack ) |
Python : Question about Python internals . If I execute import abc then Python reads the module into a new namespace and binds the variable abc in the global namespace to point to the new namespace.If I execute from abc import xyz then it reads the entire module abc into some new namespace and then binds the variable x... | Executing ` from abc import xyz ` where does the module ` abc ` go ? |
Python : I want to write this statement : however np.where can not write & ( and ) logic . How do I write this case when logic in the np.where in python . Thanks <code> def custom_asymmetric_train ( y_true , y_pred ) : residual = ( y_true - y_pred ) .astype ( `` float '' ) grad = np.where ( residual > 0 , -2*10.0*resid... | How to write a case when like statement in numpy array |
Python : I have a pd.Series with duplicated indices , and each index containing a set of booleans : What I 'm trying to do for each different index in an efficient way , is to keep only as True the first and last True values of the sequence , and set the rest to False . There can also be False values between those that... | Groupby search first and last True values |
Python : I would like to implement a function , that would multiply all elements in list by two . However my problem is that lists can have different amount of dimensions.Is there a general way to loop/iterate multidimensional list and for example multiply each value by two ? EDIT1 : Thanks for the fast answers . For t... | Python : Iterating lists with different amount of dimensions , is there a generic way ? |
Python : I tried to reflect an existing oracle database into sqlalchemy metadata : This returns the following : I have tried to import native types and also the types from dialect oracle usingbut it seems it does not recognize BINARY_DOUBLE typeI am using SQLAlchemy , version ' 1.2.1 ' <code> from sqlalchemy import cre... | How to reflect an oracle database with BINARY_DOUBLE type columns |
Python : Huh , for some reason I ca n't seem to get F working properly even on the simplest of models . Here on Django 1.9.x.In the simplest form , TestAccountBut according to this : https : //docs.djangoproject.com/en/1.9/ref/models/instances/ # updating-attributes-based-on-existing-fields it should work ... Why F is ... | Django F does n't seem to work ? |
Python : I have an input dataframe which can be generated from the code given belowThe input dataframe looks like as shown belowThis is what I didThough it works , I am afraid that this may not be the best approach . As we might have more than 200 columns and 50k RECORDS . Any help to improve my code further is very he... | Create a new column based on previous row value and delete the current row |
Python : I have a process that is essentially just an infinite loop and I have a second process that is a timer . How can I kill the loop process once the timer is done ? I want the python script to end once the timer is done . <code> def action ( ) : x = 0 while True : if x < 1000000 : x = x + 1 else : x = 0def timer ... | How to kill a process using the multiprocessing module ? |
Python : I have two classes A and B , each one storing references to objects of the other class in lists : Now , my app builds two lists , one of objects of A , one of objects of B , having cross references.Obviously , if I call json.dumps ( ) on either list_of_ ... , I get a circular reference error.What I want to do ... | What would be the pythonic way to go to prevent circular loop while writing JSON ? |
Python : I 'm trying to have a mutually exclusive group between different groups : I have the arguments -a , -b , -c , and I want to have a conflict with -a and -b together , or -a and -c together . The help should show something like [ -a | ( [ -b ] [ -c ] ) ] .The following code does not seem to do have mutually excl... | Using mutually exclusive between groups |
Python : I have to check a lot of worlds if they are in string ... code looks like : how to make it more readable and more clear ? <code> if `` string_1 '' in var_string or `` string_2 '' in var_string or `` string_3 '' in var_string or `` string_n '' in var_string : do_something ( ) | How to make it shorter ( Pythonic ) ? |
Python : I need a list-like object that will `` autogrow '' whenever a slot number greater or equal to its length is accessed , filling up all the newly created slots with some pre-specified default value . E.g. : Thanks ! PS . I know it is not hard to implement a class like this , but I avoid wheel-reinvention as much... | Autogrowing list in Python ? |
Python : I have the following python3 code : and when I run it on Python 3.6.3 ( v3.6.3:2c5fed8 , Oct 3 2017 , 18:11:49 ) [ MSC v.1900 64 bit ( AMD64 ) ] on win32 I get the following outputWhy is n't it outputting doing instance check ? The documentation says the __instancecheck__ method needs to be defined on the meta... | Why is n't __instancecheck__ being called ? |
Python : Right now , I have this code : I have used Boost here and then but I could n't really remember any simple way to write it somewhat like I would maybe write it in Python , e.g . : Is there any construct in STL/Boost to write it more or less like this ? Or maybe an equivalent to this Python Code : Mostly I am wo... | simplify simple C++ code -- something like Pythons any |
Python : I am trying to find all the nearest neighbors which are within 1 KM radius . Here is my script to construct tree and search the nearest points , From what I read in pysal page , it says - kd-tree built on top of kd-tree functionality in scipy . If using scipy 0.12 or greater uses the scipy.spatial.cKDTree , ot... | Optimize scipy nearest neighbor search |
Python : I 'm trying to multiply two 2D arrays that were transformed with fftpack_rfft2d ( ) ( SciPy 's FFTPACK RFFT ) and the result is not compatible with what I get from scipy_rfft2d ( ) ( SciPy 's FFT RFFT ) .The image below shares the output of the script , which displays : The initialization values of both input ... | How to multiply two 2D RFFT arrays ( FFTPACK ) to be compatible with NumPy 's FFT ? |
Python : I 'm trying to use a generator with a Python class that works somewhat similarly to a linked list . Here is a really simple example of what I mean : Of course this is just an example , but it 's enough to illustrate the point.Now , I was expecting to be able to invoke something like : And have the cycle stop w... | Yield on recursive data structure |
Python : I have a df which has 1 columnI have other dataframe df2which has 2 columnsI want to replace such words in my df , which occurs in original column of my df2and replace with corresponding words in correct column.and store the new strings in other dataframe df_newIs it possible without using loops and iteration ... | Replace rows of strings in dataframe with corresponding words in other dataframe pandas |
Python : How do you have a multiple line statement in either a list comprehension or eval ? I was trying to turn this code : Into a lambda function like so : In both x is a string such as 'onomatopoeia ' and y is a list such as [ ' o ' , ' a ' , ' o ' ] .But for some reason , it returns a syntax error . Can anyone expl... | Python 2 list comprehension and eval |
Python : ProblemGiven a list of string find the strings from the list that appear in the given text . Example 'red ' because it has 'shared ' has 'red ' as a substringThis is very similar to this question except that the word we need to look for can be substring as well . The list is pretty large and increases with inc... | Given a list of words and a sentence find all words that appear in the sentence either in whole or as a substring |
Python : I noticed a strange performance hit from a minor refactoring that replaced a loop with a call to the builtin max inside a recursive function.Here 's the simplest reproduction I could produce : Both f1 and f2 calculate factorial using the standard recursion but with an unnecessary maximization added in ( just s... | Why does max ( iterable ) perform much slower than an equivalent loop ? |
Python : I have a program set up so that it displays a FileChooserDialog all by itself ( no main Gtk window , just the dialog ) .The problem I 'm having is that the dialog does n't disappear , even after the user has selected the file and the program has seemingly continued executing.Here 's a snippet that showcases th... | How to hide a Gtk+ FileChooserDialog in Python 3.4 ? |
Python : I have list like this : I count item from that list : then I get : I want to get key from counter , so i do this : and I get sorted list like this : but I need an output like this ( not sorted ) : Sorry for my bad english . <code> Pasang = [ 0 , 4 , 4 , 5 , 1 , 7 , 6 , 7 , 5 , 7 , 4 , 9 , 0 , 10 , 1 , 10 , ...... | Counter list python 2.7 |
Python : Is there a construct in java that does something like this ( here implemented in python ) : Today I 'm using something like : And to me the first way looks a bit smarter . <code> [ ] = [ item for item in oldList if item.getInt ( ) > 5 ] ItemType newList = new ArrayList ( ) ; for ( ItemType item : oldList ) { i... | Java oneliner for list cleanup |
Python : I need to retrieve the definition of an acronym based on the number of letters enclosed in parentheses . For the data I 'm dealing with , the number of letters in parentheses corresponds to the number of words to retrieve . I know this is n't a reliable method for getting abbreviations , but in my case it will... | Retrieve definition for parenthesized abbreviation , based on letter count |
Python : Given a list of slices , how do I separate a sequence based on them ? I have long amino-acid strings that I would like to split based on start-stop values in a list . An example is probably the most clear way of explaining it : The extra parentheses are to show which elements were selected from the split_point... | Given a list of slices , how do I split a sequence by them ? |
Python : Lets 's say I have an enumerator , is it possible to get the property that follows ? So if I had today=Days.Sunday would I be able to do something like tomorrow=today.next ( ) ? example : I know I could use tuples ( like below ) to do something like tomorrow=today [ 1 ] , but I was hoping there was something b... | Get next enumerator constant/property |
Python : The default SQLAlchemy behavior for compiling in_ expressions is pathological for very large lists , and I want to create a custom , faster , compiler for the operator . It does n't matter to the application if the solution is a new operator ( i.e . : in_list_ ) or if it overrides the default compiler for in_ ... | New/override SQLAlchemy operator compiler output |
Python : I have a dataframe and perform a groupby with unique after filtering via a mask . My grouper series is categorical . I am using Python 3.6.0 / Pandas 0.19.2.This works as expected . Now with nunique I would expect [ 1 , 2 , 0 ] .But instead I see [ 1 , 1 , 0 ] : If I omit conversion to categorical , the result... | Groupby nunique versus unique with categorical data |
Python : Why does list ( next ( iter ( ( ) ) ) for _ in range ( 1 ) ) return an empty list rather than raising StopIteration ? The same thing happens with a custom function that explicitly raises StopIteration : <code> > > > next ( iter ( ( ) ) ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in ... | Why does list ( next ( iter ( ( ) ) ) for _ in range ( 1 ) ) == [ ] ? |
Python : I want to create an indicator variable that will propagate to all rows with the same customer-period value pair as the indicator . Specifically , if baz is yes , I want all rows of that same customer and period email to show my indicator.I 've triedwhich returnsBut this is the desired output : I 'm not sure ho... | propagate conditional column value in pandas |
Python : Given a single integer and the number of bins , how to split the integer into as equal parts as possible ? E.g . the sum of the outputs should be equals to the input integerAnother e.g . I 've tried this : It works but there must be a simpler/better way , maybe using bisect or numpy ? Using numpy from https : ... | Split an integer into bins |
Python : In Python3 , returns False , butreturns True . So I would assume based on this example alone , == has precedence over is.However , returns True . Andreturns True . Butreturns False . In this case , it would seem as if is has precedence over ==.To give another example , and this expression is n't meant to do an... | Python is , == operator precedence |
Python : I would like to make a module that makes it very simple to build click commands that share a lot of options . Those options would be distilled into a single object that is passed into the command . As an illustrative example : The total command would then have many -- magic- ... options that go into the magic ... | Commands with multiple common options going into one argument using custom decorator |
Python : I 'm trying to mimic the WWII Enigma machine in Python code , following some reading in Wikipedia and other dedicated sources . Currently , I got a machine that scrambles input text and can revert the scrambled output back to input if the configuration is reset . But the problem is the code is not yielding the... | Enigma replica not yielding expected result |
Python : In Python , __init__ used to initialize a class : what 's the equivalent method of init in Perl 6 ? Is the method new ? <code> class Auth ( object ) : def __init__ ( self , oauth_consumer , oauth_token=None , callback=None ) : self.oauth_consumer = oauth_consumer self.oauth_token = oauth_token or { } self.call... | what 's the equivalent method of __init__ in Perl 6 ? |
Python : i am coding on a dataset [ 23,25,28,28,32,33,35 ] according to wiki and scipy docIQR = Q3 − Q1 = 33 - 25 = 8when I run IQR on a dataset , the result ( 6 ) is not as expected ( 8 ) .I tried another method in https : //stackoverflow.com/a/23229224 , and the result is 6.here is my codewhat leads to the problem ? ... | Is scipy.stats doing wrong calculation for iqr ? |
Python : my Python class has some variables that require work to calculate the first time they are called . Subsequent calls should just return the precomputed value.I do n't want to waste time doing this work unless they are actually needed by the user.So is there a clean Pythonic way to implement this use case ? My i... | Pythonic way to only do work first time a variable is called |
Python : I 've built a neural network with keras using the mnist dataset and now I 'm trying to use it on photos of actual handwritten digits . Of course I do n't expect the results to be perfect but the results I currently get have a lot of room for improvement.For starters I test it with some photos of individual dig... | Improve real-life results of neural network trained with mnist dataset |
Python : At the risk of being a bit off-topic , I want to show a simple solution for loading large csv files in a dask dataframe where the option sorted=True can be applied and save a significant time of processing.I found the option of doing set_index within dask unworkable for the size of the toy cluster I am using f... | dask set_index from large unordered csv file |
Python : I 'm trying to shade the marker of an errorbar plot , without shading the error bar lines.Here 's a MWE : Also , how do I get rid of the marker edges without changing the capsize ? If I put markeredgewidth = 0 the capsize gets reset.Updated code : <code> import matplotlib.pyplot as pltx = [ 1 , 2 , 3 , 4 ] y =... | Shade error bar marker without shading error bar line |
Python : When implementing a custom equality function for a class , does it make sense to check for identity first ? An example : This interesting is for cases when the other criteria may be more expensive ( e.g . comparing some long strings ) . <code> def __eq__ ( self , other ) : return ( self is other ) or ( other c... | Does it make sense to check for identity in __eq__ ? |
Python : In my Django model , I defined a @ property which worked nicely and the property can be shown in the admin list_display without any problems . I need this property not only in admin but in my code logic in other places as well , so it makes sense to have it as property for my model . Now I wanted to make the c... | How to implement sorting in Django Admin for calculated model properties without writing the logic twice ? |
Python : This only happens on Linux ( possible OS X also , ca n't test atm ) , works fine on Windows.I have a wx.ProgressDialog that is spawned with the main thread . I send the work off to another thread , and it periodically calls back to a callback function in the main thread that will update the ProgressDialog or ,... | wx.ProgressDialog causing seg fault and/or GTK_IS_WINDOW failure when being destroyed |
Python : I have a data frame that looks like the following I was wondering if there exist a fastest way to create a python dict in pandas that would hold data like followingHere the keys are users ids and the values are uniques list of dates.This can be done early in core python but was wondering if there is a pandas o... | How to get dict of first two indexes for multi index data frame |
Python : I 'm developing an app using a Python library urllib and it is sometimes rising exceptions due to not being able to access an URL.However , the exception is raised almost 6 levels into the standard library stack : I usually run the code in ipython3 with the % pdb magic turned on so in case there is an exceptio... | Stop at exception in my , not library code |
Python : EDIT : I 'm redoing the question entirely . The issue has nothing to do with time.time ( ) Here 's a program : This program , when saved as a file and run with IDLE in Python 3.4 , takes about 10 seconds , even though 0.0 is printed out from time.time ( ) . The issue is very clearly with IDLE , because when ru... | Why does IDLE 3.4 take so long on this program ? |
Python : I 'm using previous demand to predict future demand , using 3 variables , but whenever I run the code my Y axis shows errorIf I use only one variable on the Y axis separately it has no error.Example : DATASETSCRIPTOUTPUTGitHub : repository <code> demandaY = bike_data [ [ 'cnt ' ] ] n_steps = 20for time_step in... | Recurrent neural networks for Time Series with Multiple Variables - TensorFlow |
Python : I 'd like to solve y = ( x+1 ) **3 - 2 for x in sympy to find its inverse function.I tried using solve , but I did n't get what I expected . Here 's what I wrote in IPython console in cmd ( sympy 1.0 on Python 3.5.2 ) : I was looking at the last element in the list in Out [ 4 ] , but it does n't equal x = ( y+... | How can I solve y = ( x+1 ) **3 -2 for x in sympy ? |
Python : I have some Python / Numpy code that is running slow and I think it is because of the use of a double for loop . Here is the code.I am trying to remove the double for loop and vectorize Z . Here is my attempt . This does n't work - I get the following error : So somewhere in trying to vectorize Z , I messed up... | How do I vectorize this double for loop in Numpy ? |
Python : I 'm trying to get rid of explicit binding between my models . Thus instead of using ForeignKey , I 'll use IntegerField to just store the primary key of target model as a field . Thus I 'll handle the relationship manually at code level . This is because , I 'll have to move my some schemas to different datab... | Using nested serializers with explicit ForeignKey binding replaced with raw IntegerField |
Python : I have a regular expression like this : What I am trying to do is to replace each occurrence with an associated replacement word from a list so that the end sentence would look like this : I tried using re.sub inside a for loop enumerating over replacement but it looks like re.sub returns all occurrences . Can... | Replacing each match with a different word |
Python : Given are two python lists with strings in them ( names of persons ) : I want a mapping of the names , that are most similar.Is there a neat way to do this in python ? The lists contain in average 5 or 6 Names . Sometimes more , but this is seldom . Sometimes it is just one name in every list , which could be ... | Given two python lists of same length . How to return the best matches of similar values ? |
Python : Largest product in a gridProblem 11In the 20×20 grid below , four numbers along a diagonal line have been marked in red . The product of these numbers is 26 × 63 × 78 × 14 = 1788696.What is the greatest product of four adjacent numbers in the same direction ( up , down , left , right , or diagonally ) in the 2... | Project Euler # 11 Numpy way |
Python : How would you iterate through a list of lists , such as : and construct a new list by grabbing the first item of each list , then the second , etc . So the above becomes this : <code> [ [ 1,2,3,4 ] , [ 5,6 ] , [ 7,8,9 ] ] [ 1 , 5 , 7 , 2 , 6 , 8 , 3 , 9 , 4 ] | Python Iterate through list of list to make a new list in index sequence |
Python : I encounter the following small annoying dilemma over and over again in Python : Option 1 : cleaner but slower ( ? ) if called many times since a_list get re-created for each call of do_something ( ) Option 2 : Uglier but more efficient ( spare the a_list creation all over again ) What do you think ? <code> de... | Python : How expensive is to create a small list many times ? |
Python : i can silence and restore sys.stdout this way : i know i 'd better be using contextlib.redirect_stdout which probably does something similar but my question is : why does the above code work ? i 'd have assumed python would call things like sys.stdout.write ( ) so whatever i replace sys.stdout with should have... | why does sys.stdout = None work ? |
Python : I need to know WHY this fails : When I run the code , i receive the following msg : < snip > ConfigurationError.py '' , line 7 , in __init__self.args [ 0 ] =self.__prettyfi ( self.args [ 0 ] ) TypeError : 'tuple ' object does not support item assignmentI edited the line no . to match this code sample.I do not ... | python tuples and lists . A tuple that refuses to convert |
Python : How to get the month of maximum runoffI want to get the month of maximum runoff for each year , and for the time series as a whole . The idea is to characterise global seasonality by looking at the month of max runoff . I then want to try and consider whether each pixel has a unimodal or bimodal regime.I want ... | python get month of maximum value xarray |
Python : Python functions have a descriptors . I believe that in most cases I should n't use this directly but I want to know how works this feature ? I tried a couple of manipulations with such an objects : What is the obj and what is the type ? Sure that I ca n't do this trick with functions which take no arguments .... | How work pre-defined descriptors in functions ? |
Python : I would like to ask what is the cheapest data type ( in term of memory consumption and cost to hold/process it ) to be used as dummy value in python dict ( only key of the dict matters to me , values are just placeholder ) For examples : Here only keys ( 1 , 2 , 3 ) are useful to me , the values are not so the... | Python - What is the cheapest data type to be used as `` dummy value '' in dict |
Python : Sometime , I ca n't identify when or what 's causing it , pdb will not help you with code like : You end up with the usual prompt , but trying to access e will lead to : It 's not all the time of course , and it happens on linux , windows , my machine , my colleague machine ... <code> try : foo ( ) except Exce... | Why ca n't pdb access a variable containing an exception ? |
Python : Background : I 'm a very experienced Python programmer who is completely clueless about the new coroutines/async/await features . I ca n't write an async `` hello world '' to save my life.My question is : I am given an arbitrary coroutine function f. I want to write a coroutine function g that will wrap f , i.... | Python coroutines : Release context manager when pausing |
Python : Update : not sure if this is possible without some form of a loop , but np.where will not work here . If the answer is , `` you ca n't '' , then so be it . If it can be done , it may use something from scipy.signal.I 'd like to vectorize the loop in the code below , but unsure as to how , due to the recursive ... | Recursion : account value with distributions |
Python : I 'm experiencing an odd issue with a SWIG-generated Python wrapper to a C++ class , wherein I can not seem to use the standard accessor functions of std : :map when it is wrapped as a std : :shared_ptr type . I managed to produce a MWE that reproduces the odd behavior I am observing.TestMap.hAnd then my SWIG ... | SWIG : Using std : :map accessors with a shared_ptr ? |
Python : This article describes how Python looks up an attribute on an object when it executes o.a . The priority order is interesting - it looks for : A class attribute that is a data-descriptor ( most commonly a property ) An instance attributeAny other class attributeWe can confirm this using the code below , which ... | In Python , why do properties take priority over instance attributes ? |
Python : I have the following Python code and output : When I run this in R , the results do not match : I know the differences are pretty minor , but this is a bit of an issue with my application . Also of note , the R results match Stata 's results too.Note : I 'm using Python 2.7.2 , NumpPy 1.6.1 , R 2.15.2 GUI 1.53... | Any ideas why R and Python 's NumPy scaling of vectors is not matching ? |
Python : Why does doing the above operation in two steps result in the transpose of doing it in one step ? <code> import numpy as npx = np.random.randn ( 2 , 3 , 4 ) mask = np.array ( [ 1 , 0 , 1 , 0 ] , dtype=np.bool ) y = x [ 0 , : , mask ] z = x [ 0 , : , : ] [ : , mask ] print ( y ) print ( z ) print ( y.T ) | Numpy 3D array transposed when indexed in single step vs two steps |
Python : In a related question I learned that if I have an array of shape MxMxN , and I want to select based on a boolean matrix of shape MxM , I can simply do and be done with it . Unfortunately , now I have my data in a different order : For each element in data indexed i0 , i1 , i2 , it should be selected , if selec... | 2d boolean selection in 3d matrix |
Python : I 'm trying to format a list of integers with Python and I 'm having a few difficulties achieving what I 'd like . Input is a sorted list of Integers : I would like it the output to be a String looking like this : So far all I managed to achieve is this : I 'm having trouble to tell my code to ignore a Int if ... | Formatting consecutive numbers |
Python : While my startup is in dark mode I want all access except access to / to go to a screener page where users have enter a password given to them by a representative . I 've come up with the following simple middleware to perform the task . Just to be clear , this is intended to ensure that users agree to keep th... | Security issues with a middleware screener page |
Python : I 'm pip-installing my module like so : When I later import the module from within Python , can I somehow detect if the module is installed in this editable mode ? Right now , I 'm just checking if there 's a .git folder in os.path.dirname ( mymodule.__file__ ) ) which , well , only works if there 's actually ... | How to detect if module is installed in `` editable mode '' ? |
Python : What algorithm can I use to find the set of all positive integer values of n1 , n2 , ... , n7 for which the the following inequalities holds true.For example one set n1= 2 , n2 = n3 = ... = n7 =0 makes the inequality true . How do I find out all other set of values ? The similar question has been posted in M.S... | find the set of integers for which two linear equalities holds true |
Python : I have a dataframe like the following : I am trying to clean my dataframe in the following way : For every row having more value than 1.5 times the previous row value or less than 0.5 times the previous row value , drop it.But If the previous row is a to-drop row , comparison must be made with the immediate pr... | Filtering rows from dataframe based on the values of the previous rows |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.