lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | If we have x = type ( a ) and x == y , does it necessarily imply that x is y ? Here is a counter-example , but it 's a cheat : And I could not create a counterexample like this : To clarify my question - without overriding equality operators to do something insane , is it possible for a class to exist at two different ... | > > > class BrokenEq ( type ) : ... def __eq__ ( cls , other ) : ... return True ... > > > class A ( metaclass=BrokenEq ) : ... pass ... > > > a = A ( ) > > > x = type ( a ) > > > x == A , x is A ( True , True ) > > > x == BrokenEq , x is BrokenEq ( True , False ) > > > A1 = type ( ' A ' , ( ) , { } ) > > > A2 = type (... | Are classobjects singletons ? |
Python | This actually stems from a discussion here on SO.Short versionmeta ( ) is called when Klass class declaration is executed.Which part of the ( python internal ) code actually calls meta ( ) ? Long versionWhen the class is declared , some code has to do the appropriate attribute checks and see if there is a __metaclass__... | def meta ( name , bases , class_dict ) return type ( name , bases , class_dict ) class Klass ( object ) : __metaclass__ = meta class Meta ( type ) : passclass A : __metaclass__ = MetaA.__class__ == Meta class Meta ( type ) : def __new__ ( cls , class_name , bases , class_dict ) : return type ( class_name , bases , clas... | Who calls the metaclass |
Python | I have the following python code that generates a list of anonymous functions : I would have expected it to be equivalent to However , whereas the second snippet prints out 0 which is what I would expect , the first prints 2 . What 's wrong with the first snippet of code , and why does n't it behave as expected ? | basis = [ ( lambda x : n*x ) for n in [ 0 , 1 , 2 ] ] print basis [ 0 ] ( 1 ) basis = [ ( lambda x : 0*x ) , ( lambda x : 1*x ) , ( lambda x : 2*x ) ] print basis [ 0 ] ( 1 ) | Generating a list of functions in python |
Python | I am new to GEKKO and also to modeling bioreactors , so I might be missing something obvious.I have a system of 10 ODEs that describe a fed-batch bioreactor . All constants are given . The picture below shows the expected behavior of this model ( extracted from a paper ) . However , the only feasible solution I found i... | import numpy as npfrom gekko import GEKKOimport matplotlib.pyplot as pltm = GEKKO ( remote=False ) # create GEKKO model # constants 3L continuous fed-batchKdQ = 0.001 # degree of degradation of glutamine ( 1/h ) mG = 1.1*10**-10 # glucose maintenance coefficient ( mmol/cell/hour ) YAQ = 0.90 # yield of ammonia from glu... | GEKKO Infeasible system of ODE equations of a fed-batch Bioreactor |
Python | What is the best way to reshape a df so it stacks columns based on a similarity in column name while keeping the unique ID portion of the column name in a new column ? I have a df similar to the following ( my actual data also includes NaN values that need to remain ) : However I need it to look like this : I tried to ... | df = pandas.DataFrame ( { `` RX_9mm '' : scipy.randn ( 5 ) , `` RY_9mm '' : scipy.randn ( 5 ) , '' TX_9mm '' : scipy.randn ( 5 ) , `` TY_9mm '' : scipy.randn ( 5 ) , `` RX_10mm '' : scipy.randn ( 5 ) , `` RY_10mm '' : scipy.randn ( 5 ) , '' TX_10mm '' : scipy.randn ( 5 ) , `` TY_10mm '' : scipy.randn ( 5 ) , `` time ''... | Python reshaping based on column names keeping ID & other rows |
Python | Why do this happen ? Is it intentional or is the integer just falling through a crack ? Does it have to do with : I 'm running Numpy 1.8.0.dev-74b08b3 and Python 2.7.3 | > > > map ( numpy.all , range ( -2 , 3 ) ) [ -2 , -1 , 0 , 1 , 2 ] > > > map ( numpy.all , [ False , True ] ) [ False , True ] | numpy.all with integer arguments returns an integer |
Python | I am new to regex , why does this not output 'present ' ? | tale = `` It was the best of times , ... far like the present ... of comparison only . `` a = re.compile ( ' p ( resent ) ' ) print a.findall ( tale ) > > > > [ 'resent ' ] | Regex in Python - Using groups |
Python | How can you make a class method static after the class is defined ? In other words , why does the third case fail ? | > > > class b : ... @ staticmethod ... def foo ( ) : ... pass ... > > > b.foo ( ) > > > class c : ... def foo ( ) : ... pass ... foo = staticmethod ( foo ) ... > > > c.foo ( ) > > > class d : ... def foo ( ) : ... pass ... > > > d.foo = staticmethod ( d.foo ) > > > d.foo ( ) Traceback ( most recent call last ) : File `... | Create staticmethod from an existing method outside of the class ? ( `` unbound method '' error ) |
Python | I have created a basic app using Django 's built in authentication system . I successfully created a User object in the shell using > > python manage.py createsuperuser.I then created a basic view , 'UserLogin ' along with corresponding serializers/urls , to log an existing user in using the django.contrib.auth authent... | class UserLogin ( APIView ) : def post ( self , request , format = None ) : serializer = UserLoginSerializer ( data=request.data ) if serializer.is_valid ( ) : user = authenticate ( username=serializer.validated_data [ `` username '' ] , password=serializer.validated_data [ `` password '' ] ) if user is not None : logi... | django.contrib.auth.login ( ) function not returning any user as logged in |
Python | How would I get the person with the first last name in the following : So far I was doing : Is this the recommended way to do this , or are there better alternatives ? | l = [ 'John Fine ' , 'Doug Biro ' , 'Jo Ann Alfred ' ] -- > Jo Ann Alfred sorted ( l , key=itemgetter ( -1 ) ) [ 0 ] | Sort by last name |
Python | So I was wondering how I can , using Python 2.7 , most efficiently take a list of values used to represent indices like this : ( but with a length of up to 250,000+ ) and remove that list of indices from a larger list like this : ( 3,000,000+ items ) to get a result like this : I 'm looking for an efficient solution mo... | indices = [ 2 , 4 , 5 ] numbers = [ 2 , 6 , 12 , 20 , 24 , 40 , 42 , 51 ] [ 2 , 6 , 20 , 42 , 51 ] | What is the most efficient way to remove a group of indices from a list of numbers in Python 2.7 ? |
Python | I 've been experimenting with a number of techniques but I 'm sure there 's smooth-ish way to get this done.Suppose I have two lists with the same amount of items in them ( 4 each ) : I 'd like to merge these lists in all possible ways while retaining order . Example outputs : The point is each of the lists must retain... | a = [ ' a ' , ' b ' , ' c ' , 'd ' ] b = [ 1 , 2 , 3 , 4 ] a , b , c , d , 1 , 2 , 3 , 4 1 , 2 , 3 , 4 , a , b , c , d a , b , 1 , 2 , c , 3 , 4 , d a , b , **d** , c , 1 ... > d precedes c whereas c is before d in the original list1 , **4** , a , b , 3 ... . > 4 precedes 3 whereas 3 is before 4 in the original list a ... | Merging 2 Lists In Multiple Ways - Python |
Python | I have two very large python lists that look like this : These lists go on to very large numbers , but I specify a maximum value , say 100 and after that I can discard the rest.Now I need to calculate for each value ( 0,1,2..100 ) the ratio : occurrences in list A / occurrences in list B . And since this value is not a... | List A : [ 0,0,0,0,0,0,0,1,1,1,1,2,2,3,3,3,4 ... ... ... ] List B : [ 0,0,0,0,0,0,2,2,2,2,3,3,4,4 ... ... ... ] 0 : 7/6=1.166 1 : 9/6 = 1.52 : 9/6 = 1.53 : 9/6 = 1.5 ... 100 : some_number | Efficiently counting items in large python lists |
Python | I am searching for a way to change the printable output of an Exception to a silly message in order to learn more about python internals ( and mess with a friend ; ) , so far without success.Consider the following codeThe code shall output name ' x ' is not definedI would like the change that output to the name ' x ' y... | try : x # is not definedexcept NameError as exc : print ( exc ) from forbiddenfruit import cursecurse ( BaseException , 'repr ' , lambda self : print ( `` Test message for repr '' ) ) curse ( BaseException , 'str ' , lambda self : print ( `` Test message for str '' ) ) try : xexcept NameError as exc : print ( exc.str (... | Python change Exception printable output , eg overload __builtins__ |
Python | I want to test a presence of a key in a dictionary as 'if key is not in dictionary : do something ' I have already done this already multiple times , but this time it behaves strangely.particularly : returns KeyErrorwhen I debugged this code in Eclipse PyDev , i got the following ( using expressions ) : Do anyone under... | termCircuit = termCircuitMap [ term ] term in termCircutiMap # prints Falseterm in termCircuitMap.keys ( ) # prints True | python 2.7 presence in a dictionary |
Python | I am currently implementing a MINLP optimization problem in Python GEKKO for determining the optimal operational strategy of a trigeneration energy system . As I consider the energy demand during all periods of different representative days as input data , basically all my decision variables , intermediates , etc . are... | `` `` '' Created on Fri Nov 22 10:18:33 2019 @ author : julia '' '' '' # __Get GEKKO & numpy___from gekko import GEKKOimport numpy as np # ___Initialize model___m = GEKKO ( ) # ___Global options_____m.options.SOLVER = 1 # APOPT is MINLP Solver # ______Constants_______ i = m.Const ( value=0.05 ) n = m.Const ( value=10 )... | Python GEKKO MINLP optimization of energy system : How to build intermediates that are 2D arrays |
Python | I have the following endpoint starting an Authorization flow : Then I get redirect back from Spotify to /callback , where I am setting jwt cookies in my response , like so : And cookies show up in my browser console , under 'Application'.Now I would like to get them from another endpoint , like so : But I 'm printing t... | @ spotify_auth_bp.route ( `` /index '' , methods= [ 'GET ' , 'POST ' ] ) def spotify_index ( ) : CODE = `` code '' CLIENT_ID = os.environ.get ( 'SPOTIPY_CLIENT_ID ' ) SCOPE = os.environ.get ( 'SPOTIPY_SCOPE ' ) REDIRECT_URI = os.environ.get ( 'SPOTIPY_REDIRECT_URI ' ) SPOTIFY_AUTH_URL = `` https : //accounts.spotify.co... | Flask - unable to get cookies |
Python | I struggle to come up with a title that describes what I 'm trying to solve , so please comment if you have a better title ! The solution can be in R , Python , or SQL ( Aster TeraData SQL to be exact , though a solution any SQL language is very helpful for learning purposes ) The problem : Given a list of pairs of ite... | colone = c ( `` a '' , '' b '' , '' u '' , '' e '' , '' f '' , '' f '' , '' j '' , '' z '' ) coltwo = c ( `` b '' , '' c '' , '' c '' , '' a '' , '' g '' , '' h '' , '' h '' , '' y '' ) d < - data.frame ( colone , coltwo ) d colone coltwo1 a b2 b c3 u c4 e a5 f g6 f h7 j h8 z y ( a , b , c , e , u ) ( f , g , h , j ) (... | R / SQL /Python : Extracting connected components from node-edge pairs |
Python | I have a function for getting an item from a dict : I 'll be mapping this function via multiprocessing to look up values from a series of very long dicts : I feel like I should n't have to define a function for getting a value from a dict . Is there some inbuilt way to do this ? | def dict_lookup ( dictionary , key ) : return dictionary [ key ] dictlist = [ { } , { } , { } ] dict_lookup_partial = functools.partial ( dict_lookup , key=some_key ) with multiprocessing.Pool ( ) as pool : values = pool.map ( dict_lookup_partial , dictlist ) | Map dict lookup |
Python | I am implementing a Kalman filter in numpy . It works fine , except for when I import matplotlib.pyplot to visualize the result : The complete code is here . Let me emphasize that it seems to work correctly before I do the import ; it prints a 100 x 2 array of numbers that are plausible . After adding the import , even... | import numpy as np import matplotlib.pyplot as plt # adding this line breaks thingsimport sys | Random nan errors when importing matplotlib.pyplot |
Python | I want to use plotly to display a graph only after a button is clicked but am not sure how to make this work . My figure is stored in the following code bitI then define my app layout with the following code bit : But the problem is i only want the button displayed at first . Then when someone clicks on the forecast bu... | fig1 = go.Figure ( data=plot_data , layout=plot_layout ) app.layout = html.Div ( [ # button html.Div ( className='submit ' , children= [ html.Button ( 'Forecast ' , id='submit ' , n_clicks=0 ) ] ) , # loading dcc.Loading ( id= '' loading-1 '' , type= '' default '' , children=html.Div ( id= '' loading-output-1 '' ) ) , ... | Plotly : How to display graph after clicking a button ? |
Python | Here I am trying to update each product image of a particular product . But it is not working properly . Here only the image of first object is updating.There is a template where we can update product and product images at once . ProductImage has a ManyToOne relation with Product Model so in the template there can be m... | Traceback ( most recent call last ) : File `` venv\lib\site-packages\django\core\handlers\exception.py '' , line 47 , in inner response = get_response ( request ) File `` venv\lib\site-packages\django\core\handlers\base.py '' , line 179 , in _get_response response = wrapped_callback ( request , *callback_args , **callb... | 'tuple ' object has no attribute '_committed ' error while updating image objects ? |
Python | Here , I use Google Vision API to detect text from the following image . The red box indicates samples of a combined bounding box that I would like to obtain.Basically , I get the text output and bounding box from the above image . Here , I would like to merge the bounding boxes and texts that are located along the sam... | [ { 'description ' : 'บริษัทไปรษณีย์ไทย ' , 'vertices ' : [ ( 528 , 202 ) , ( 741 , 202 ) , ( 741 , 222 ) , ( 528 , 222 ) ] } , { 'description ' : ' จํากัด ' , 'vertices ' : [ ( 754 , 204 ) , ( 809 , 204 ) , ( 809 , 222 ) , ( 754 , 222 ) ] } , ... [ { 'description ' : 'บริษัทไปรษณีย์ไทยจำกัด ' , 'vertices ' : [ ( 528 ,... | Combining nearby bounding boxes along one axis |
Python | The output is : I ca n't mentally navigate whatever logic is going on here to produce this output . I am aware of the zip function to make this code behave in the way I clearly intend it to ; but I 'm just trying to understand why it works this way when you do n't use the zip function.Is this a deliberate functionality... | x , y , z = [ 1,2,3 ] , [ 4,5,6 ] , [ 7,8,9 ] for a , b , c in x , y , z : print ( a , b , c ) 1 2 34 5 67 8 9 | What 's going on in this code ? |
Python | The Multiprocessing module is quite confusing for python beginners specially for those who have just migrated from MATLAB and are made lazy with its parallel computing toolbox . I have the following function which takes ~80 Secs to run and I want to shorten this time by using Multiprocessing module of Python . This out... | from time import timexmax = 100000000start = time ( ) for x in range ( xmax ) : y = ( ( x+5 ) **2+x-40 ) if y < = 0xf+1 : print ( 'Condition met at : ' , y , x ) end = time ( ) tt = end-start # total timeprint ( 'Each iteration took : ' , tt/xmax ) print ( 'Total time : ' , tt ) Condition met at : -15 0Condition met at... | How to retrieve values from a function run in parallel processes ? |
Python | If I have a very simple ( although possibly very complex ) function generator in Python 2.7 , like so : Which can be used , like so : What would be a simple wrapper for another function generator that produces the same result , except multiplied by 2 ? The above function generator is simple , but please assume it is to... | def accumulator ( ) : x = yield 0 while True : x += yield x > > > a = accumulator ( ) > > > a.send ( None ) 0 > > > a.send ( 1 ) 1 > > > a.send ( 2 ) 3 > > > a.send ( 3 ) 6 def doubler ( ) : a = accumulator ( ) a.send ( None ) y = yield 0 while True : y = 2 * a.send ( yield y ) def doubler ( ) : a = accumulator ( ) a.s... | How to map or nest Python 2.7 function generators ? |
Python | Why floor division is not working according to the rule in this case ? p.s . Here Python is treating 0.2 as 0.20000000001 in the floor division caseSo ( 12/0.2000000001 ) is resulting in 59.999999 ... And floor ( 59.999999999 ) outputting 59But do n't know why python is treating 0.2 as 0.2000000001in the floor division... | > > > print ( 12//0.2 ) 59.0 > > > print ( floor ( 12/0.2 ) ) 60 | How is floor division not giving result according to the documented rule ? |
Python | I am making a simple Object-oriented projectile simulation program in python.I am just using the Turtle and Math modules . The problem is when I try to simply move my projectile ( as a test before integrating some equations ) it does not move.This is supposed to move my turtle , is n't it ? I do n't understand what 's ... | import turtlefrom turtle import Turtleimport mathwindow = turtle.Screen ( ) window.title ( `` Projectile '' ) window.bgcolor ( `` black '' ) window.setup ( width=800 , height=800 ) window.tracer ( 0 ) def drawLine ( ) : line = turtle.Turtle ( ) line.penup ( ) line.pencolor ( `` white '' ) line.pensize ( 10 ) line.goto ... | Python Turtle object not moving |
Python | After a failed attempt at a `` streamlined '' install of the SimpleCV framework superpack for Windows . I 'm now working through a manual installation guide ( which I 'm OK with as I have more control over the installation and might finally learn about installing Python Packages properly in Windows ! ) Rather than just... | easy_install pyreadline easy_install PIL easy_install cython easy_install pip pip install ipython pip install https : //github.com/ingenuitas/SimpleCV/zipball/1.3 easy_install pip { { { I intend to research and probably use get-pip.py here } } } pip install pyreadline pip install PIL pip install cython pip install ipyt... | Why would a python framework installation guide advise the use of easy_install for some required packages and pip for others ? |
Python | Say I have a very simple data type : And I a special kind of list to store the data type : And I store them : Is there any way for the SimpleList object to know when one of the properties of its members changes ? For example , how can I get simple_list to execute self.update_useful_property_of_list ( ) when something l... | class SimpleObject : def __init__ ( self , property ) : self.property = property def update_property ( self , value ) : self.property = value class SimpleList ( collections.MutableSequence ) : def update_useful_property_of_list ( self , value ) : self.useful_property_of_list = value simple1 = SimpleObject ( 1 ) simple2... | Is it possible to monitor a list ( or mutable sequence ) for when a member of the list is modified ? |
Python | I feel very confused about some code like this [ not written by me ] : version must be a num . when [ func1 ( ) , func2 ( ) ] is [ 1 , None ] , should return 1 , when is [ None , 2 ] , should return 2 , when [ 1 , 2 ] , should return 1.so I think it 's wrong to use any ( ) in this code , because any ( ) just return Tru... | version = any ( func1 ( ) , func2 ( ) ) # wrong , should be any ( [ func1 ( ) , func2 ( ) ] ) def func1 ( ) : if something : return 1 else : return Nonedef func2 ( ) : if something : return 2 else : return 3 | how to use python 's any |
Python | Dictionaries and lists defined directly under the class definition act as static ( e.g . this question ) How come other variables such as integer do not ? | > > > class Foo ( ) : bar=1 > > > a=Foo ( ) > > > b=Foo ( ) > > > a.bar=4 > > > b.bar1 > > > class Foo ( ) : bar= { } > > > a=Foo ( ) > > > b=Foo ( ) > > > a.bar [ 7 ] =8 > > > b.bar { 7 : 8 } | Why some class variables seem to act as static while others do n't ? |
Python | In my urls.py I have some Entries like these : This repeats for a lot of standard models where I just have to get the information , list it and be able to edit and delete it.In my views.py : It all repeats after this pattern . So for 3 models I will have 3 times mostly identical code with just minor changes.How can I s... | url ( r'auftragsarten/list/ $ ' , generic.ListView.as_view ( queryset=Auftragsart.objects.order_by ( 'name ' ) , paginate_by=25 ) , name='auftragsarten_liste ' ) , url ( r'^auftragsarten/form/ $ ' , views.auftragsarten_form , name='auftragsarten_form ' ) , url ( r'auftragsarten/update/ ( ? P < pk > [ \d ] + ) / $ ' , v... | DRY approach for Django |
Python | So I talked with some colleagues and the problem I currently have is actually quite challenging . The context behind this problem has to do with mass spectrometry and assigning structure to different peaks that the software gives.But to break it down into a optimization problem , I have a certain target value . I also ... | List of inputs : [ 18.01 , 42.01 , 132.04 , 162.05 , 203.08 , 176.03 ] Target value : 1800.71 [ 18.01 , 162.05 , 162.05 , 162.05 , 162.05 , 162.05 , 162.05 , 162.05 , 162.05 , 162.05 , 162.05 , 162.05 ] **which gives a sum of 1800.59** [ 18.01 , 18.01 , 203.08 , 203.08 , 203.08 , 162.05 , 203.08 , 18.01 , 18.01 , 18.01... | Finding all possible combinations whose sum is within certain range of target |
Python | I am but a humble coding grasshopper and have a simple question.Let : How come : outputs an empty list like expected , yet : is an error ? Ditto for strings , please and thank you . | x = [ 'this ' , 'is ' , ' a ' , 'list ' ] x [ 100:101 ] x [ 100 ] | Why does python allow list [ a : b ] but not list [ a ] if a and b are out of index range ? |
Python | I want to generate combinations that associate indices in a list with `` slots '' . For instance , ( 0 , 0 , 1 ) means that 0 and 1 belong to the same slot while 2 belongs to an other . ( 0 , 1 , 1 , 1 ) means that 1 , 2 , 3 belong to the same slot while 0 is by itself . In this example , 0 and 1 are just ways of ident... | > > > LEN , SIZE = ( 3,1 ) > > > list ( itertools.product ( range ( SIZE+1 ) , repeat=LEN ) ) > > > [ ( 0 , 0 , 0 ) , ( 0 , 0 , 1 ) , ( 0 , 1 , 0 ) , ( 0 , 1 , 1 ) , ( 1 , 0 , 0 ) , ( 1 , 0 , 1 ) , ( 1 , 1 , 0 ) , ( 1 , 1 , 1 ) ] > > > [ ( 0 , 0 , 0 ) , ( 0 , 0 , 1 ) , ( 0 , 1 , 0 ) , ( 0 , 1 , 1 ) ] def test ( ) : for... | Generating a list of repetitions regardless of the order |
Python | Suppose I have a data frame which have column x , a , b , c And I would like to aggregate over a , b , c to get a value y from a list of x via a function myfun , then duplicate the value for all rows within each window/partition.In R in data.table this is just 1 line : dt [ , y : =myfun ( x ) , by=list ( a , b , c ) ] ... | # To simulate rows in a data frame class Record : def __init__ ( self , x , a , b , c ) : self.x = x self.a = a self.b = b self.c = c # Assume we have a list of Record as df mykey = attrgetter ( ' a ' , ' b ' , ' c ' ) for key , group_iter in itertools.groupby ( sorted ( df , key=mykey ) , key=mykey ) : group = list ( ... | What is pythonic way to do dt [ , y : =myfun ( x ) , by=list ( a , b , c ) ] in R ? |
Python | new to python and trying to wrestle with the finer points of assignment operators . Here 's my code and then the question.the above code , returns 5 the first time , but yet -4 upon the second print . In my head I feel that the number should actually be 4 as I am reading this as x= x - x +4 . However , I know that is w... | x = 5 print ( x ) x -= x + 4 print ( x ) | why does x -= x + 4 return -4 instead of 4 |
Python | Suppose that I am using a library X that specifies for example that exception.BaseError is the base class for all exceptions of X.Now , there is another exception , say X.FooError , which of course inherits from exception.BaseError but is more generalized , let 's say that it handles invalid input . Let 's suppose ther... | X |BaseError |FooError | Deciding which exceptions to catch in Python |
Python | I am studying a little about the source code of Python and I decided to put into practice some changes in the grammar , so I downloaded the source code of version 3.7.I am following the guidelines of PEP 0306 : https : //www.python.org/dev/peps/pep-0306/And from the example of Hackernoon : https : //hackernoon.com/modi... | @ testdef mydef ( self ) : pass decorated : decorators ( classdef | funcdef | async_funcdef ) @ testid : int = 1 annassign : ' : ' test [ '= ' test ] # or even use small_stmt decorated : decorators ( classdef | funcdef | async_funcdef | annassign ) [ ... ] assert ( TYPE ( CHILD ( n , 1 ) ) == funcdef || TYPE ( CHILD ( ... | Python Source Code - Update Grammar |
Python | I 'm a newbie in Python . After reading some chapters of Python Tutorial Release 2.7.5 , I 'm confused about Python scopes and namespaces . This question may be duplicated because I do n't know what to search for . I created a class and an instance . Then I deleted the class using del . But the instance still works pro... | > > > class MyClass : # define a class ... def greet ( self ) : ... print 'hello ' ... > > > instan = MyClass ( ) # create an instantiation > > > instan < __main__.MyClass instance at 0x00BBCDC8 > > > > instan.greet ( ) hello > > > dir ( ) [ 'instan ' , 'MyClass ' , '__builtins__ ' , '__doc__ ' , '__name__ ' , '__packa... | Why does an object still work properly without the class |
Python | I 'm trying to create a pandas dataframe from a dictionary . The dictionary is set up asI would like the dataframe to include only `` y1 '' and `` y2 '' . So far I can accomplish this using I would like to know if it is possible to accomplish this without having df.drop ( ) | nvalues = { `` y1 '' : [ 1 , 2 , 3 , 4 ] , `` y2 '' : [ 5 , 6 , 7 , 8 ] , `` y3 '' : [ a , b , c , d ] } df = pd.DataFrame.from_dict ( nvalues ) df.drop ( `` y3 '' , axis=1 , inplace=True ) | Creating a Pandas dataframe from elements of a dictionary |
Python | Why doesgive [ ( 0 , 0 ) , ( 1 , 1 ) , ( 2 , 2 ) , ( 3 , 3 ) , ( 4 , 4 ) ] butgive [ ( 0 , 1 ) , ( 2 , 3 ) ] ? I always though that generator were iterators , so iter on a generator was a no-op.For example , is the same as ( The same is true for Python 3 , but with list ( zip ( and range . ) | zip ( * [ xrange ( 5 ) ] *2 ) zip ( * [ iter ( xrange ( 5 ) ) ] *2 ) list ( iter ( xrange ( 5 ) ) ) [ 0 , 1 , 2 , 3 , 4 ] list ( xrange ( 5 ) ) [ 0 , 1 , 2 , 3 , 4 ] | Calling multiple iterators on xrange objects |
Python | I want to create a set of command-line utilities in python that would be used like so : Very similar to django management commands . Is there any library that eases the creation of such commands ? | python utility.py command1 -option arg | Is there a Python library that eases the creation of CLI utilities like Django management commands ? |
Python | I 'm trying to understand why I can iterate along the string . What I see in the documentation is : One method needs to be defined for container objects to provide iteration support : container.__iter__ ( ) Return an iterator object . The object is required to support the iterator protocol described below . If a contai... | > > > dir ( 'aa ' ) [ '__add__ ' , '__class__ ' , '__contains__ ' , '__delattr__ ' , '__doc__ ' , '__eq__ ' , '__format__ ' , '__ge__ ' , '__getattribute__ ' , '__getitem__ ' , '__getnewargs__ ' , '__getslice__ ' , '__gt__ ' , '__hash__ ' , '__init__ ' , '__le__ ' , '__len__ ' , '__lt__ ' , '__mod__ ' , '__mul__ ' , '_... | Why is it possible to iterate along a string ? |
Python | PyCharm community edition 3.4.1 running for Python 2.7.8.Simple code : Gives'Null is not callable'In the shell this code executes error-free . | def test ( x ) : print xd= { 'test ' : test } d [ 'test ' ] ( 5 ) d [ 'test ' ] ( 5 ) | Python : Is PyCharm broken ? Or i am broken maybe ? Or both ? |
Python | Suppose I wanted to write a function similar to rangeRecall that range has a one argument and 2/3 argument form : If I wanted the method or function to have the same interface , is there a more elegant way than this : | class range ( object ) | range ( stop ) - > range object | range ( start , stop [ , step ] ) - > range object def range_like ( *args ) : start , stop , step= [ None ] *3 if len ( args ) ==1 : stop=args [ 0 ] elif len ( args ) ==2 : start , stop=args elif len ( args ) ==3 : start , stop , step=args else : raise ValueErr... | Function definition like range |
Python | Without specifying the equality comparison properties of objects , Python is still doing something when using > and < . What is Python actually comparing these objects by if you do n't specify __gt__ or __lt__ ? I would expect an unsupported operand error here , as you get when trying to add two objects together withou... | In [ 1 ] : class MyObject ( object ) : ... : pass ... : In [ 2 ] : class YourObject ( object ) : ... : pass ... : In [ 3 ] : me = MyObject ( ) In [ 4 ] : you = YourObject ( ) In [ 5 ] : me > youOut [ 5 ] : FalseIn [ 6 ] : you > meOut [ 6 ] : True | Custom class ordering : no error thrown , what is Python testing for ? |
Python | I try to understand Theano implementation of LSTM ( at the moment the link does not work for whatever reason but I hope it will be back soon ) .In the code I see the following part : To make it `` context independent '' I rewrite it in the following way : where dimension of x is ( n1 , n2 ) and dimension of W is ( N , ... | emb = tparams [ 'Wemb ' ] [ x.flatten ( ) ] .reshape ( [ n_timesteps , n_samples , options [ 'dim_proj ' ] ] ) e = W [ x.flatten ( ) ] ] .reshape ( [ n1 , n2 , n3 ] ) e = W [ x ] emb = tparams [ 'Wemb ' ] [ x ] | Do we need to use flatten and reshape in Theano if we use a matrix of indexes ? |
Python | When running the celery worker then each line of the output of the pprint is always prefixed by the timestamp and also is being stripped . This makes it quite unreadable : Is there a way how to tell celery not to format the output of pprint ? UPDATE : the question was placed a bit wrong . The desired output would look ... | [ 2015-11-05 16:01:12,122 : WARNING/Worker-2 ] { [ 2015-11-05 16:01:12,122 : WARNING/Worker-2 ] u'key1 ' [ 2015-11-05 16:01:12,122 : WARNING/Worker-2 ] : [ 2015-11-05 16:01:12,122 : WARNING/Worker-2 ] 'value1 ' [ 2015-11-05 16:01:12,122 : WARNING/Worker-2 ] , u'_id ' : [ 2015-11-05 16:01:12,122 : WARNING/Worker-2 ] Obj... | How to remove timestamps from celery pprint output ? |
Python | Here is simple example of code : I have saved it to file and run . It works : But here is the trick : It also works with undeclared option fil.Why it behaves in that way ? | from optparse import OptionParserparser = OptionParser ( ) parser.add_option ( `` -f '' , `` -- file '' , dest= '' filename '' ) ( options , args ) = parser.parse_args ( ) print options $ python script.py -- file some_name { 'filename ' : 'some_name ' } $ python script.py -- fil some_name { 'filename ' : 'some_name ' } | optparse - why the last char of the option can be ignored ? With ` -- file ` it behaves same as ` -- fil ` |
Python | I have a list of points in 3d coordinates system ( X , Y , Z ) . Moreover , each of them have assigned a float value v , so a single point might be described as ( x , y , z , v ) . This list is represented as a numpy array of shape= ( N,4 ) . For each 2d position x , y I need to get the maximum value of v. A straightfo... | for index in range ( points.shape [ 0 ] ) : x = points [ index , 0 ] y = points [ index , 1 ] v = points [ index , 3 ] maxes [ x , y ] = np.max ( maxes [ x , y ] , v ) | Numpy : proper way of getting maximum from a list of points |
Python | There is a dict params : What I want to do is if value == 'DIMENSION ' , change its name to 'element_n ' , where n is the key 's position.So my desired output isSo far I did itBut it does n't change anything | { 'channel ' : 'DIMENSION ' , 'day ' : 'DIMENSION ' , 'subscribersGained ' : 'METRIC ' , 'likes ' : 'METRIC ' , 'views ' : 'METRIC ' , 'subscribersLost ' : 'METRIC ' } { 'element_1 ' : 'DIMENSION ' , 'element_2 ' : 'DIMENSION ' , 'subscribersGained ' : 'METRIC ' , 'likes ' : 'METRIC ' , 'views ' : 'METRIC ' , 'subscrib... | How to change the value of a key in dict in Python with its position ? |
Python | I 'm trying to simplify my solution to Project Euler 's problem 11 ( find the greatest product of 4-in-a-row numbers in a 20x20 grid ) .My main gripe with my answer are the four try/except clauses in the definition of sub_lists_at_xy . I have one for each direction ( east , south , southeast , and southwest ) of 4-in-a... | from operator import mulwith open ( `` 11.txt '' ) as f : nums = [ [ int ( num ) for num in line.split ( ' ' ) ] for line in f.read ( ) .split ( '\n ' ) ] def prod ( lst ) : return reduce ( mul , lst , 1 ) def sub_lists_at_xy ( array , length , x , y ) : try : east=array [ y ] [ x : x+length ] except IndexError : east=... | How to DRY up directional logic from a try/except mess |
Python | I have the following snippit of code : This produces a plot which looks like this : As you can see i have explicitly mentioned the xytext , this makes the `` bubbles '' messy as at some locations they overlap which makes it hard to read . Is there any way it can be `` auto - placed '' so that they are not overlapping .... | data.plot ( y='Close ' , ax = ax ) newdates = exceptthursday.loc [ start : end ] for anotate in ( newdates.index + BDay ( ) ) .strftime ( ' % Y- % m- % d ' ) : ax.annotate ( 'holliday ' , xy= ( anotate , data [ 'Close ' ] .loc [ anotate ] ) , xycoords='data ' , xytext= ( -30 , 40 ) , textcoords='offset points ' , size=... | Auto place annotation bubble |
Python | New to Python here.I am looking for a simple way of creating a list ( Output ) , which returns the count of the elements of another objective list ( MyList ) while preserving the indexing ( ? ) .This is what I would like to get : I found solutions to a similar problem . Count the number of occurrences for each element ... | MyList = [ `` a '' , `` b '' , `` c '' , `` c '' , `` a '' , `` c '' ] Output = [ 2 , 1 , 3 , 3 , 2 , 3 ] In : Counter ( MyList ) Out : Counter ( { ' a ' : 2 , ' b ' : 1 , ' c ' : 3 } ) | List elements ’ counter |
Python | I am learning Python . I have a function readwrite ( filename , list ) . filename is of type string . list is a list containing strings to be wtitten in the file.I have a simple function call like this : I am facing problem that when i print the filename argument value inside the function definition , i get hello.txt r... | fname = 'hello.txt'readwrite ( 'xx'+fname , datalist ) def readwrite ( fileName , list ) : print 'arg file= ' , filename curdir = os.getcwd ( ) ; fullpath = os.path.join ( curdir , filename ) ; print ( 'full path calculated as : '+fullpath ) ; fileExist = os.path.exists ( fullpath ) ; if ( fileExist ) : print 'file exi... | Python Functions Confusion |
Python | I would like to draw a box across multiple axes , using one ax coordinates as reference . The simple code I have , that does not generate the box isThis generate the following figure : What I would like to have is the following figure , using x cordinates from ax2 to specify the position : | import matplotlib.pyplot as pltimport numpy as npfig , ( ax1 , ax2 ) = plt.subplots ( 2 , 1 , sharex=False , sharey=False , figsize= ( 15,9 ) ) x = 2 * np.pi * np.arange ( 1000 ) / 1000 y1 = np.sin ( x ) y2 = np.cos ( x ) ax1.plot ( x , y1 ) ax2.plot ( x , y2 ) plt.show ( ) | How draw box across multiple axes on matplotlib using ax position as reference |
Python | I 'm fairly new to python and I appreciate it 's a dynamic language . Some 30 minutes into my first python code , I 've discovered that the bytes type behaves a little strange ( to say the least ) : Try it here : http : //ideone.com/NqbcHkNow , the docs say strings and bytes behave very similarly with the exception of ... | a = bytes ( ) print type ( a ) // prints : < type 'str ' > | Why is type ( bytes ( ) ) < 'str ' > |
Python | In Julia , calling a function with the @ edit macro from the REPL will open the editor and put the cursor at the line where the method is defined . So , doing this : jumps to julia/base/int.jl and puts the cursor on the line : As does the function form : edit ( + , ( Int , Int ) ) Is there an equivalent decorator/funct... | julia > @ edit 1 + 1 ( + ) ( x : :T , y : :T ) where { T < : BitInteger } = add_int ( x , y ) | What 's the Python equivalent of Julia 's ` @ edit ` macro ? |
Python | Here is my problem : I manipulate 432*46*136*136 grids representing time* ( space ) encompassed in numpy arrays with numpy and python . I have one array alt , which encompasses the altitudes of the grid points , and another array temp which stores the temperature of the grid points.It is problematic for a comparison : ... | def interpolation_extended ( self , temp , alt ) : [ t , z , x , y ] =temp.shape new=np.zeros ( [ t,220 , x , y ] ) for l in range ( 0 , t ) : for j in range ( 0 , z ) : for lat in range ( 0 , x ) : for lon in range ( 0 , y ) : new [ l , conv ( alt [ l , j , lat , lon ] ) , lat , lon ] =temp [ l , j , lat , lon ] retur... | Python numpy grid transformation using universal functions |
Python | I 've tried to always declare class attributes inside the __init__ for clarity and organizational reasons . Recently , I 've learned that strictly following this practice has extra non-aesthetic benefits too thanks to PEP 412 being added for Python 3.3 . Specifically , if all attributes are defined in the __init__ , th... | class Dog : def __init__ ( self ) : self.height = 5 self.weight = 25class Cat : def __init__ ( self ) : self.set_shape ( ) def set_shape ( self ) : self.height = 2 self.weight = 10 | Does declaring variables in a function called from __init__ still use a key-sharing dictionary ? |
Python | I have a Python app with a Firebase-database backend.When I retrieve the data from my database , I want to check if those valuesare available ( if not , that means that the database is somehow corrupted , as mandatories fields are missing ) My current implementation is the following : This works fine , is compact , but... | self.foo = myDbRef.get ( 'foo ' ) self.bar = myDbRef.get ( 'bar ' ) self.bip = myDbRef.get ( 'bip ' ) self.plop = myDbRef.get ( 'plop ' ) if self.foo is None or self.bar is None or self.bip is None or self.plop is None : self.isValid = False return ErrorCode.CORRUPTED_DATABASE if self.foo is None : self.isValid = False... | Python check if one or more values is None and knows which ones are |
Python | I have this codeNow , how does this work ? Does it traverse the whole list comparing the element ? Does it use some kind of hash function ? Also , is it the same for this code ? | list = [ ' a ' , ' b ' , ' c ' ] if ' b ' in list : return `` found it '' return `` not found '' list.index ( ' b ' ) | Python : How does `` IN '' ( for lists ) works ? |
Python | For yesterday 's Pi Day , Matt Harper published a video in which he approximated Pi by rolling two 120-sided dice 500 times ( see the video here ) . Basically , for each pair of random numbers , you have to check whether they are coprime or not . Then , the formulais calculated.His result was about 3.05 which is rather... | pi = sqrt ( 6/ ( n_coprimes/n_cofactors ) ) # EDIT : Wrong premise . Misremembered the formula . import randomfrom math import gcd , sqrtdef pi ( cp , cf ) : return sqrt ( 6/ ( cf/cp ) ) # EDIT : Second error - switched numerator/denominator ... coprime = 0cofactor = 0iterations = 1000000for i in range ( iterations ) :... | Why does n't my program approximate pi ? |
Python | Why in the following program is an IndentationError being raised rather than SyntaxError ? To make sure the IDLE was n't just acting funny , I also tested this code by running it from a normal source file . The same exception type is still being raised . The versions of Python I used to test this were Python 3.5.2 and ... | > > > if True : ... print `` just right ! '' File `` < stdin > '' , line 2 print `` just right ! '' ^IndentationError : Missing parentheses in call to 'print ' | Why is an IndentationError being raised here rather than a SyntaxError ? |
Python | I was given a challenge by a friend to build an efficient Fibonacci function in python . So I started testing around different ways of doing the recursion ( I do not have high math skills to think of a complex algorithm , and please do not show me an efficient Fibonacci function , that is not the question ) .Then I tri... | def fibo ( n ) : if n > 1 : return fibo ( n-1 ) +fibo ( n-2 ) return 1 def fibo ( n ) : if n < 1 : return 1 return fibo ( n-1 ) +fibo ( n-2 ) res = map ( fibo , range ( 35 ) ) print res | What 's the efficiency difference between these ( almost identical ) conditions |
Python | How can I modify the code below so that the plot spans all 6 x-axis values , and just has blank spots at A , C , F for df2 's bars ? | import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsdf = pd.DataFrame ( { ' x ' : [ ' A ' , ' B ' , ' C ' , 'D ' , ' E ' , ' F ' ] , 'y1 ' : np.random.rand ( 6 ) } ) df2 = pd.DataFrame ( { ' x ' : [ ' B ' , 'D ' , ' E ' ] , 'y2 ' : np.random.rand ( 3 ) } ) fig , axes = plt.subplots ... | Matplotlib sharex on data with different x values ? |
Python | Looking at this snippet of python code I wrote : ( Hoping it 's self-explanatory ) I 'm wondering if python has a better way to do it ? I learned python several months ago , wrote a couple scripts , and have n't used it much since . It puts me in a weird spot for learning because I know enough to do what I want but do ... | return map ( lambda x : x [ 1 ] , filter ( lambda x : x [ 0 ] == 0b0000 , my_func ( i ) ) ) | Is there a better way to do this python code ? |
Python | I have a list , with a specific order : And some sub lists with elements of the main list , but with an different order : How can I apply the order of L to L1 and L2 ? For example , the correct order after the processing should be : I am trying something like this , but I am struggling how to set the new list with the ... | L = [ 1 , 2 , 5 , 8 , 3 ] L1 = [ 5 , 3 , 1 ] L2 = [ 8 , 1 , 5 ] L1 = [ 1 , 5 , 3 ] L2 = [ 1 , 5 , 8 ] new_L1 = [ ] for i in L1 : if i in L : print L.index ( i ) # get the order in L | Apply the order of list to another lists |
Python | I 'm encountering a problem with incorrect numpy calculations when the inputs to a calculation are a numpy array with a 32-bit integer data type , but the outputs include larger numbers that require 64-bit representation.Here 's a minimal working example : The desired output is that the numpy array contains the correct... | arr = np.ones ( 5 , dtype=int ) * ( 2**24 + 300 ) # arr.dtype defaults to 'int32 ' # Following comment from @ hpaulj I changed the first line , which was originally : # arr = np.zeros ( 5 , dtype=int ) # arr [ : ] = 2**24 + 300single_value_calc = 2**8 * ( 2**24 + 300 ) numpy_calc = 2**8 * arrprint ( single_value_calc )... | Error with numpy array calculations using int dtype ( it fails to cast dtype to 64 bit automatically when needed ) |
Python | Attempted problem : The probability that one of two dice will have a higher value than a third die.Problem : For some reason , when I use the random module from python ( specifically the sample method ) , I end up with a different ( and incorrect ) result from when when I use numpy . I 've included the results at the b... | import numpy as np import random random_list = [ ] numpy_list = [ ] n= 500 np_wins = 0 rand_wins = 0 for i in range ( n ) : rolls = random.sample ( range ( 1,7 ) , 3 ) rand_wins += any ( rolls [ 0 ] < roll for roll in rolls ) rolls = np.random.random_integers ( 1 , 6 , 3 ) np_wins += any ( rolls [ 0 ] < roll for roll i... | Python random not working like |
Python | I have a two time series in separate pandas.dataframe , the first one - series1 has less entries and different start datatime from the second - series2 : How can I resample series2 to match the DatetimeIndex of series1 ? | index1 = pd.date_range ( start='2020-06-16 23:16:00 ' , end='2020-06-16 23:40:30 ' , freq='1T ' ) series1 = pd.Series ( range ( len ( index1 ) ) , index=index1 ) index2 = pd.date_range ( '2020-06-16 23:15:00 ' , end='2020-06-16 23:50:30 ' , freq='30S ' ) series2 = pd.Series ( range ( len ( index2 ) ) , index=index2 ) | Pandas : resample a dataframe to match a DatetimeIndex of a different dataframe |
Python | In this case , why does x += y produce a different result than x = x + y ? | import numpy as npx = np.repeat ( [ 1 ] , 10 ) y = np.random.random ( len ( x ) ) x += yprint x # Output : [ 1 1 1 1 1 1 1 1 1 1 ] x = x + yprint x # Output : [ 1.50859536 1.31434732 1.15147365 1.76979431 1.64727364 # 1.02372535 1.39335253 1.71878847 1.48823703 1.99458116 ] | Numpy , why does ` x += y ` produce a different result than ` x = x + y ` ? |
Python | I need to try a string against multiple ( exclusive - meaning a string that matches one of them ca n't match any of the other ) regexes , and execute a different piece of code depending on which one it matches . What I have currently is : Apart from the ugliness , this code matches against all regexes even after it has... | m = firstre.match ( str ) if m : # Do somethingm = secondre.match ( str ) if m : # Do something elsem = thirdre.match ( str ) if m : # Do something different from both elif m = secondre.match ( str ) | How do I search through regex matches in Python ? |
Python | I 'm so far out of my league on this one , so I 'm hoping someone can point me in the right direction . I think this is an optimization problem , but I have been confused by scipy.optimize and how it fits with pulp . Also , matrix math boggles my mind . Therefore this problem has really been slowing me down without to ... | # fake data for the internetdata = { 'customerid ' : [ 101,102,103,104,105,106,107,108,109,110 ] , 'prob_CHOICEA ' : [ 0.00317,0.00629,0.00242,0.00253,0.00421,0.00414,0.00739,0.00549,0.00658,0.00852 ] , 'prob_CHOICEB ' : [ 0.061,0.087,0.055,0.027,0.022,0.094,0.099,0.072,0.018,0.052 ] , 'prob_CHOICEC ' : [ 0.024,0.013,0... | Optimization help involving matrix operations and constraints |
Python | I am trying to process a file that looks more or less like this : I know I can for example use Python shlex to parse those without major issues with something like : I can then do a for loop and iterate over the key value pairs.Results in : So far so good but I am having trouble finding an efficient way of outputting t... | f=0412345678 t=0523456789 t=0301234567 s=Party ! flag=urgent flag=english id=1221AB12 entry = `` f=0412345678 t=0523456789 t=0301234567 s=Party ! flag=urgent flag=english id=1221AB12 '' line = shlex.split ( entry ) row = { } for kvpairs in line : key , value = kvpairs.split ( `` = '' ) row.setdefault ( key , [ ] ) .app... | Python : Convert multiple instances of the same key into multiple rows |
Python | I 've created a script to log in to linkedin using requests . The script is doing fine . After logging in , I used this url https : //www.linkedin.com/groups/137920/ to scrape this name Marketing Intelligence Professionals from there which you can see in this image . The script can parse the name flawlessly . However ,... | import jsonimport requestsfrom bs4 import BeautifulSouplink = 'https : //www.linkedin.com/login ? fromSignIn=true & trk=guest_homepage-basic_nav-header-signin'post_url = 'https : //www.linkedin.com/checkpoint/lg/login-submit'target_url = 'https : //www.linkedin.com/groups/137920/'with requests.Session ( ) as s : s.head... | Ca n't extract a link connected to ` see all ` button from a webpage |
Python | I have a list containing thousands of sub-lists . Each of these sub-lists contain a combination of mixed strings and boolean values , for example : I want to sort this list in accordance with the contents of the sub-lists , like : I 've tried sorting it like this : This does n't work because of the combination of boole... | lst1 = [ [ ' k ' , ' b ' , False ] , [ ' k ' , ' a ' , True ] , [ ' a ' , ' a ' , ' a ' ] , [ ' a ' , ' b ' , ' a ' ] , [ ' a ' , ' a ' , False ] , ... ] lst2 = [ [ ' a ' , ' a ' , ' a ' ] , [ ' a ' , ' a ' , False ] , [ ' a ' , ' b ' , ' a ' ] , [ ' k ' , ' a ' , True ] , [ ' k ' , ' b ' , False ] , ... ] lst2 = sorte... | How to sort a list of sub-lists by the contents of sub-lists , where sub-lists contain strings and booleans ? |
Python | In apache beam python sdk , I often see ' > > ' operator in pipeline procedure.https : //beam.apache.org/documentation/programming-guide/ # pipeline-ioWhat does this mean ? | lines = p | 'ReadFromText ' > > beam.io.ReadFromText ( 'path/to/input-*.csv ' ) | What does the redirection mean in apache beam ( python ) |
Python | I am new to Python . I was recently confused by a syntax `` [ list ] * k '' . I want to understand how Python actually executes it . Example : Assume len ( list ) = n , when Python interprets it , I have following guesses with my limited knowledge.it uses list.extend ( list ) method.Thus it will take up O ( n * k ) spa... | > > > l = [ 1 , 2 ] * 10 > > > l [ 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 ] > > > l [ 3 ] = 100 > > > l [ 1 , 2 , 1 , 100 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 , 1 , 2 ] size = Py_SIZE ( a ) * n ; p = np- > ob_item ; items = a- > ob_item ; for ( i = 0 ; i < n ; i... | How Python execute [ list ] * num ? what 's time complexity and memory complexity ? |
Python | The is operator compares the memory addresses of two objects , and returns True if they 're the same . Why , then , does it not work reliably with strings ? Code # 1Code # 2I have created two strings whose content is the same but they are living on different memory addresses . Why is the output of the is operator not c... | > > > a = `` poi '' > > > b = `` poi '' > > > a is bTrue > > > ktr = `` today is a fine day '' > > > ptr = `` today is a fine day '' > > > ktr is ptrFalse | Confused about ` is ` operator with strings |
Python | I have a pandas dataframe : I would like to count the frequency of each item in the list and construct a table like the following : I look at pandas.explode but I do n't think that is what I want.I can do something like this below . But I feel like there might be a more efficient way to do this . I have about 3.5 milli... | | items -- -- -- -- -- -- -- 0 | [ a ] 1 | [ a , b ] 2 | [ d , e , f , f ] 3 | [ d , f , e ] 4 | [ c , a , b ] a| b| c| d| e| f -- -- -- -- -- -- -- -- -- -- -- -- -0| 1| 0| 0| 0| 0| 01| 1| 1| 0| 0| 0| 02| 0| 0| 0| 1| 1| 23| 0| 0| 0| 1| 1| 14| 1| 1| 1| 0| 0| 0 import pandas as pdfrom collections import Counter , defaul... | Convert list of rows to frequency table in Pandas |
Python | This is my attempt to program the Mandelbrot set in Python 3.5 using the Pygame module.I believe that the iteration algorithm is correct , but the output does n't look right : Wondering what might be the problem ? Sorry for the code dump , just not sure which part may cause it to look like that . | import math , pygamepygame.init ( ) def mapMandelbrot ( c , r , dim , xRange , yRange ) : x = ( dim-c ) /dim y = ( dim-r ) /dim # print ( [ x , y ] ) x = x* ( xRange [ 1 ] -xRange [ 0 ] ) y = y* ( yRange [ 1 ] -yRange [ 0 ] ) x = xRange [ 0 ] + x y = yRange [ 0 ] + y return [ x , y ] def checkDrawBox ( surface ) : for ... | Mandelbrot set displays incorrectly |
Python | I 'm trying to evaluate the exponential of a symbolic array . Basically I have a numeric array a and a symbolic variable x defined . I then defined a function f which is equal to the exponential of the multiplication of the two , and tried to evaluate the result for a given value of x : But the following error happens ... | import numpy as npfrom sympy import * # Declaration of variablesa=np.array ( [ 1 , 2 ] ) x = Symbol ( ' x ' ) f=exp ( a*x ) # Function evaluationf=f.subs ( x , 1 ) print ( f.evalf ( ) ) AttributeError : 'ImmutableDenseNDimArray ' object has no attribute '_eval_evalf ' | Evaluation of the exponential of a symbolic array in Python |
Python | I have the following doctest written x.doctest : But when I ran python -m doctest x.doctest on python 2.7.11 , the doctest did n't recognize from __future__ import division : Even when I shifted the future import statement to the first line : The doctest still fails : Why is that so and how can I resolve this ? Is ther... | This is something : > > > x = 3 + 4foo bar something else : > > > from __future__ import division > > > y = 15 > > > z = int ( '24 ' ) > > > m = z / y > > > print ( m ) 1.6 **********************************************************************File `` x.doctest '' , line 11 , in x.doctestFailed example : print ( m ) Exp... | Doctest not recognizing __future__.division |
Python | In Python , I can do : In Rust , I can force the behavior of k=3 by : But what if I wanted k=4 or k=5 ? | from itertools import productk = 3for kmer in product ( `` AGTC '' , repeat=k ) : print ( kmer ) # [ macro_use ] extern crate itertools ; for kmer in iproduct ! ( `` AGTC '' .chars ( ) , `` AGTC '' .chars ( ) , `` AGTC '' .chars ( ) ) { println ! ( `` { : ? } '' , kmer ) ; } | In Rust , what is the proper way to replicate Python 's `` repeat '' parameter in itertools.product ? |
Python | Now I have two objectsmy_class1 = MyClass ( x ) my_class2 = MyClass ( ) I want to use x when this my_class2 object is calledAs other languages Support static variable like java , c++ etc . | class MyClass ( Object ) : def __init__ ( self , x=None ) : if x : self.x = x def do_something ( self ) : print self.x | Python : How to use First Class Object Constructor value In another Object |
Python | I have a python dictionary containing 3 lists in the keys 'time ' , 'power ' and 'usage'.All the lists have the same number of elements and all the lists are sorted . WhatI want to do is to sum up all the elements for lists 'power ' and 'usage ' that their indexescorrespond to the same value in list 'time ' , so as to ... | { 'time ' : [ 1 , 2 , 2 , 3 , 4 , 4 , 5 ] , 'power ' : [ 2 , 2 , 3 , 6 , 3 , 3 , 2 ] , 'usage ' : [ 0 , 1 , 1 , 2 , 1 , 4 , 7 ] } { 'time ' : [ 1 , 2 , 3 , 4 , 5 ] , 'power ' : [ 2 , 5 , 6 , 6 , 2 ] , 'usage ' : [ 0 , 2 , 2 , 5 , 7 ] } d = { 'time ' : [ 1,2,2,3,4,4,5 ] , 'power ' : [ 0,1,1,2,1,4,7 ] , 'usage ' : [ 2,2,... | How to sum 3 same sized sorted lists based on the identical elements of the first one in Python ? |
Python | I have a matrix listScore with the shape ( 100000,2 ) : I would like to count all the identical rows like . For instance , if listScore was a list of list I would simple do : to look for all the list equal to [ 2,0 ] .I could obviously transform the type of my listScore so that it would be a list but I want to keep to ... | listScore.count ( [ 2,0 ] ) | Equivalent of count list function in numpy array |
Python | I have two dataframes . Each one has a timestamp index representing the start time and a duration value ( in seconds ) which could be used to calculate the end time . The time interval and duration is different for each dataframe , and could vary within each dataframe as well.I want to join these two dataframes such th... | duration param1Start Time ( UTC ) 2017-10-14 02:00:31 60 952017-10-14 02:01:31 60 342017-10-14 02:02:31 60 102017-10-14 02:03:31 60 442017-10-14 02:04:31 60 632017-10-14 02:05:31 60 52 ... duration param2Start Time ( UTC ) 2017-10-14 02:00:00 300 932017-10-14 02:05:00 300 952017-10-14 02:10:00 300 91 ... duration param... | Pandas dataframe join on overlapped time ranges |
Python | I 'm playing around with Enigma Catalyst . Unfortunately , the documentation is rather limited.So I 'm trying to run their example `` hello world '' type algo which looks as follows : I realize according to the documentation it says you first need to `` ingest '' download the historical data which I believe I did . How... | from catalyst import run_algorithmfrom catalyst.api import order , record , symbolimport pandas as pddef initialize ( context ) : context.asset = symbol ( 'btc_usd ' ) def handle_data ( context , data ) : order ( context.asset , 1 ) record ( btc=data.current ( context.asset , 'price ' ) ) if __name__ == '__main__ ' : r... | ENIGMA CATALYST - WARNING : Loader : Refusing to download new treasury data because a download succeeded |
Python | Scala has the apply ( ) function.I am new to Python and I am wondering how should I write the following one-liner : I would feel better with something like : Am I wrong from a FF viewpoint ? Is there such construction in Python ? Edit : I know about the poorly picked snippet . | ( part_a , part_b ) = ( lambda x : re.search ( r '' ( \w+ ) _ ( \d+ ) '' , x ) .groups ( ) ) ( input_string ) ( part_a , part_b ) = input_string.apply ( lambda x : re.search ( r '' ( \w+ ) _ ( \d+ ) '' , x ) .groups ( ) ) | Python and functional programming : is there an apply ( ) function ? |
Python | I am trying to import my data regarding the changes of price of different items . The data is kept in MySQL . I have imported the input dataframe df in a stacked format similar to the following : And , in order to perform time series analysis , I want to convert to another format similar to : I have looked at this ques... | ID Type Date Price1 Price20001 A 2001-09-20 30 3010002 A 2001-09-21 31 2780003 A 2001-09-22 28 2990004 B 2001-09-18 18 1590005 B 2001-09-20 21 1570006 B 2001-09-21 21 1620007 C 2001-09-19 58 3260008 C 2001-09-20 61 4100009 C 2001-09-21 67 383 A B C Price1 Price2 Price1 Price2 Price1 Price2Date 2001-09-18 NULL NULL 18 1... | How to pivot multilabel table in pandas |
Python | I have a class : I can print the class docstring by typing : This outputs as : How can I print the docstring for Hotel which is a Class attribute/element ? What I 've triedreturns : I 've also tried the help ( ) function to no avail.N.BSphinx seems to be able to extract the docstrings of class attributes and include th... | class Holiday ( ActivitiesBaseClass ) : `` '' '' Holiday is an activity that involves taking time off work '' '' '' Hotel = models.CharField ( max_length=255 ) `` '' '' Name of hotel `` '' '' print ( Holiday.__doc__ ) Holiday is an activity that involves taking time off work print ( Holiday.Hotel.__doc__ ) A wrapper fo... | How to print docstring for class attribute/element ? |
Python | Here is my Python code that creates an infinitely nested dictionary : Here is the output : The output shows that a [ ' k ' ] refers to a itself which makes it infinitely nested.I am guessing that the statement : is behaving like : which would indeed create an infinitely nested dictionary.I looked at Section 7.2 : Assig... | a = a [ ' k ' ] = { } print ( a ) print ( a [ ' k ' ] ) print ( a [ ' k ' ] [ ' k ' ] ) print ( a is a [ ' k ' ] ) { ' k ' : { ... } } { ' k ' : { ... } } { ' k ' : { ... } } True a = a [ ' k ' ] = { } new = { } a = newa [ ' k ' ] = new | Why does a = a [ ' k ' ] = { } create an infinitely nested dictionary ? |
Python | Is there a simpler way of doing the following ? Note that it is different to itertools.repeat ( set ( ) ) , since the latter only constructs the set object once . | ( set ( ) for _ in itertools.repeat ( None ) ) | Python repeat set generator |
Python | I 'm doing examples to understand how it works python asynchronously . I read the Trio documentation and I thought that only one task can be executed in the loop every time and in every checkpoint the scheduler decide which task will be executed.I did an example to test it , in the trio example I do n't use any checkpo... | import timeimport trioresults = [ ] async def sum_numbers ( first , last ) : result = 0 for i in range ( first , last ) : result += i results.append ( result ) async def main ( ) : start_time = time.time ( ) async with trio.open_nursery ( ) as nursery : nursery.start_soon ( sum_numbers , 0 , 50000000 ) nursery.start_so... | Trio execution time without IO operations |
Python | I have two text files in the following format : The first is this on every line : Key1 : Value1The second is this : Key2 : Value2Is there a way I can replace Value1 in file1 by the Value2 obtained from using it as a key in file2 ? For example : file1 : file2 : I would like to get : There is n't necessarily a match betw... | foo : hellobar : world hello : adambar : eve foo : adambar : eve | Text processing with two files |
Python | Here is an idea for a dict subclass that can mutate keys . This is a simple self contained example that 's just like a dict but is case insensitive for str keys.dev note : if you copy my code for your own uses , you should implement LowerDict.__init__ to check for any key collisions - I have n't bothered to include tha... | from functools import wrapsdef key_fix_decorator ( f ) : @ wraps ( f ) def wrapped ( self , *args , **kwargs ) : if args and isinstance ( args [ 0 ] , str ) : args = ( args [ 0 ] .lower ( ) , ) + args [ 1 : ] return f ( self , *args , **kwargs ) return wrappedclass LowerDict ( dict ) : passfor method_name in '__setitem... | Why does n't my idea work in python2 ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.