lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I have a nested list as shown below : and I am trying to print the first element of each list using the code : But I get the following output : Required output : How to get this output in Python ? | A = [ ( ' a ' , ' b ' , ' c ' ) , ( 'd ' , ' e ' , ' f ' ) , ( ' g ' , ' h ' , ' i ' ) ] A = [ ( ' a ' , ' b ' , ' c ' ) , ( 'd ' , ' e ' , ' f ' ) , ( ' g ' , ' h ' , ' i ' ) ] print A [ : ] [ 0 ] ( ' a ' , ' b ' , ' c ' ) ( ' a ' , 'd ' , ' g ' ) | How to index nested lists in Python ? |
Python | I am using this GSDMM python implementation to cluster a dataset of text messages . GSDMM converges fast ( around 5 iterations ) according the inital paper . I also have a convergence to a certain number of clusters , but there are still a lot of messages transferred in each iteration , so a lot of messages are still c... | In stage 0 : transferred 9511 clusters with 150 clusters populated In stage 1 : transferred 4974 clusters with 138 clusters populated In stage 2 : transferred 2533 clusters with 90 clusters populated….In stage 34 : transferred 1403 clusters with 47 clusters populated In stage 35 : transferred 1410 clusters with 47 clus... | GSDMM Convergence of Clusters ( Short Text Clustering ) |
Python | I am using python 's sched module to run a task periodically , and I think I have come across a bug . I find that it relies on the time of the system on which the python script is run . For example , let 's say that I want to run a task every 5 seconds . If I forward the system time , the scheduled task will run as exp... | import schedimport timeimport threadingperiod = 5scheduler = sched.scheduler ( time.time , time.sleep ) def check_scheduler ( ) : print time.time ( ) scheduler.enter ( period , 1 , check_scheduler , ( ) ) if __name__ == '__main__ ' : print time.time ( ) scheduler.enter ( period , 1 , check_scheduler , ( ) ) thread = th... | How to schedule a periodic task that is immune to system time change using Python |
Python | I have one scenario here . Let me explain by small example.I have 10 pens , I have to give it to 3 people . Those person 's ratio are like 6:6:1 means if I am giving 1 pen to Person C I have to give 6-6 pens to Person A and Person B.I have tried to solve it by using simple calculation which I have described below . Her... | PerPersonPen = ( TotalCountofPens * PerPersonRatio ) / ( SumofAllPersonsRatio ) Person A = ( Int ) ( 10*6 ) /13 = 4Person B = ( Int ) ( 10*6 ) /13 = 4Person C = ( Int ) ( 10*1 ) /13 = 0 | assign value as per ratio defined |
Python | I 'm running Java in a GraalVM to use it to execute python.The question is how the python code should receive `` arguments '' . The graal documentation states that if this were JS , I would do something like this : Indeed , that works . The python equivalent might be : This fails , as there 's no such module . I ca n't... | Context context = Context.create ( ) ; Value v = context.getPolyglotBindings ( ) ; v.putMember ( `` arguments '' , arguments ) ; final Value result = context.eval ( `` python '' , contentsOfMyScript ) ; System.out.println ( result ) ; return jsResult ; const args = Interop.import ( 'arguments ' ) ; import Interopargs =... | Getting outer environment arguments from java using graal python |
Python | I am trying Pandas UDF and facing the IllegalArgumentException . I also tried replicating examples from PySpark Documentation GroupedData to check but still getting the error.Following is the environment configurationpython3.7Installed PySpark==2.4.5 using pipInstalled PyArrow==0.16.0 using pipOutput | from pyspark.sql.functions import pandas_udf , PandasUDFType @ pandas_udf ( 'int ' , PandasUDFType.GROUPED_AGG ) def min_udf ( v ) : return v.min ( ) sorted ( gdf.agg ( min_udf ( df.age ) ) .collect ( ) ) Py4JJavaError Traceback ( most recent call last ) < ipython-input-66-94a0a39bfe30 > in < module > -- -- > 1 sorted ... | PySpark 2.4.5 : IllegalArgumentException when using PandasUDF |
Python | I have mappings of `` stems '' and `` endings '' ( may not be the correct words ) that look like so : But much longer , of course . I also made the corresponding dictionary the other way around : I 've now tried to come up with an algorithm to find any match of two or more `` stems '' that match two or more `` endings ... | all_endings = { 'birth ' : set ( [ 'place ' , 'day ' , 'mark ' ] ) , 'snow ' : set ( [ 'plow ' , 'storm ' , 'flake ' , 'man ' ] ) , 'shoe ' : set ( [ 'lace ' , 'string ' , 'maker ' ] ) , 'lock ' : set ( [ 'down ' , 'up ' , 'smith ' ] ) , 'crack ' : set ( [ 'down ' , 'up ' , ] ) , 'arm ' : set ( [ 'chair ' ] ) , 'high '... | Finding combinations of stems and endings |
Python | How do I make this code run in under 30s to find the largest palindrome that is the product of 2 numbers with the same number of digits ? maxInt is the largest number with the specified digits . For example if you want a palindrome that is a multiple of 2 3-digit numbers you maxInt would be 999 . If you want the larges... | def palindrome ( maxInt ) : pa= [ ] for x in range ( maxInt,0 , -1 ) : for y in range ( maxInt,0 , -1 ) : num=x*y if str ( num ) == str ( num ) [ : :-1 ] : pa.append ( num ) return max ( pa ) | Fastest algorithm to find the largest palindrome that is the product of 2 numbers with the same number of digits |
Python | EDIT : Ok , all the edits made the layout of the question a bit confusing so I will try to rewrite the question ( not changing the content , but improving its structure ) .The issue in shortI have an openCL program that works fine , if I compile it as an executable . Now I try to make it callable from Python using boos... | # include < vector > # define CL_HPP_ENABLE_EXCEPTIONS # define CL_HPP_TARGET_OPENCL_VERSION 200 # define CL_HPP_MINIMUM_OPENCL_VERSION 200 // I have the same issue for 100 and 110 # include `` cl2.hpp '' # include < boost/python.hpp > using namespace std ; class TestClass { private : std : :vector < cl : :CommandQueue... | static openCL class not properly released in python module using boost.python |
Python | As part of a test suite written in Python 3 [ .4-.6 ] on Linux , I have to run a number 3rd-party tests . The 3rd-party tests are bash scripts . They are designed to run with Perl 's prove TAP harness . One bash script can contain up to a few thousands of individual tests - and some of them can hang indefinitely . Afte... | # ! /bin/bashMAXCOUNT=20echo `` 1.. $ MAXCOUNT '' for ( ( i=1 ; i < = $ MAXCOUNT ; i++ ) ) do echo `` ok $ i '' sleep 1done import sysimport timeif __name__ == '__main__ ' : maxcount = 20 print ( ' 1.. % d ' % maxcount ) for i in range ( 1 , maxcount + 1 ) : sys.stdout.write ( 'ok % d\n ' % i ) time.sleep ( 1 ) import ... | How do I run Perl 's `` prove `` TAP harness in unbuffered mode ? |
Python | For speedier testing it 's nicer to use a memory-based sqlite , but it 's still necessary once in a while to use MySQL for testing that more closely matches production.To avoid a dry discussion/abstract question , the code below inserts a couple of words and confirms they 're in the database , for both types of SQL dat... | from flask import Flaskfrom flask_sqlalchemy import SQLAlchemyimport unittestdb = SQLAlchemy ( ) TEST_DATABASE_URL_MEMORY = 'sqlite : /// : memory : 'TEST_DATABASE_URL_MYSQL = 'mysql+pymysql : //root : @ 127.0.0.1:3306/somewords'def create_app ( db_url ) : app = Flask ( __name__ ) app.config [ 'SQLALCHEMY_DATABASE_URI ... | Automating database creation for testing |
Python | I have downloaded the official conda recipe of opencv in AnacondaRecipes.I have tried to build this package executing : I am getting the following error when the recipe compiles opencv , when doing [ 72 % ] Built target opencv_dnn . The error is the following : Lookin in the $ PREFIX directory , there is not libpng fol... | conda-build recipe -c conda-forge [ 67 % ] Building CXX object modules/imgcodecs/CMakeFiles/opencv_imgcodecs.dir/src/grfmt_png.cpp.o/opt/conda/conda-bld/opencv_1521187259162/work/modules/imgcodecs/src/grfmt_png.cpp:62:10 : fatal error : libpng/png.h : No such file or directory # include < libpng/png.h > ^~~~~~~~~~~~~~c... | conda-build of official AnacondaRecipes/opencv-feedstock fails looking for libpng.h |
Python | What is the best data structure to cache ( save/store/memorize ) so many function result in database . Suppose function calc_regress with flowing definition in python : I see answers to What kind of table structure should be used to store memoized function parameters and results in a relational database ? but it seem t... | def calc_regress ( ind_key , dep_key , count=30 ) : independent_list = sql_select_recent_values ( count , ind_key ) dependant_list = sql_select_recent_values ( count , dep_key ) import scipy.stats as st return st.linregress ( independent_list , dependant_list ) | Data structure of memoization in db |
Python | i have list with lists of strings looks likei need to have output like this : have been try this : but i have error | allyears # [ [ '1916 ' ] , [ '1919 ' ] , [ '1922 ' ] , [ '1912 ' ] , [ '1924 ' ] , [ '1920 ' ] ] # [ 1916 , 1919 , 1922 , 1912 , 1924 , 1920 ] for i in range ( 0 , len ( allyears ) ) : allyears [ i ] = int ( allyears [ i ] ) > > > TypeError : int ( ) argument must be a string , a bytes-like object or a number , not 'li... | Flatten a list of lists containing single strings to a list of ints |
Python | I was trying to make a `` matplotlib cake '' . ; ) I have the following code : It should print a blue and an red rectangle , divided by a green `` coating '' .which results in the following output : As you can see the output is exactly how I expect it . Great ! However , I played with the parameters ... If I make the w... | import matplotlib.pyplot as pltdef save_fig ( layer ) : # Hide the right and top spines ax.spines [ 'right ' ] .set_visible ( False ) ax.spines [ 'top ' ] .set_visible ( False ) # Sacale axis plt.axis ( 'scaled ' ) fig.savefig ( layer+'.pdf ' , dpi=fig.dpi ) fig.savefig ( layer+'.jpeg ' , dpi=fig.dpi ) gap =10fig , ax ... | Weird behavior of matplotlib plt.Rectangle |
Python | I have a reference listAnd a dataframeI want to check which elements from reference list is present in each row , and convert into binary listI can achieve this using applyHowever , using apply on large datasets is very slow and hence I am looking to use numpy vectorization . How can I improve my performance ? Extensio... | ref = [ 'September ' , 'August ' , 'July ' , 'June ' , 'May ' , 'April ' , 'March ' ] df = pd.DataFrame ( { 'Month_List ' : [ [ 'July ' ] , [ 'August ' ] , [ 'July ' , 'June ' ] , [ 'May ' , 'April ' , 'March ' ] ] } ) df Month_List0 [ July ] 1 [ August ] 2 [ July , June ] 3 [ May , April , March ] def convert_month_to... | Check reference list in pandas column using numpy vectorization |
Python | I 'm just learning Python and Pytest and came across Fixtures . Pardon the basic question but I 'm a bit wondering what 's the advantage of using fixtures in Python as you can already pass a method as argument , for example : What would be the advantage of passing a @ pytest.fixture object as argument instead ? | def method1 ( ) : return 'hello world'def method2 ( methodToRun ) : result = methodToRun ( ) return resultmethod2 ( method1 ) | Using Fixtures vs passing method as argument |
Python | I am new at python and I 'm currently exploring some of its core functionalities.Could you explain me why the following example always return false in case of a string with special characters : I understand that the storage positions are different for strings with special characters on each assignment , I already check... | > > > a= '' x '' > > > b= '' x '' > > > a is bTrue > > > a= '' xxx '' > > > b= '' xxx '' > > > a is bTrue > > > a= '' xü '' > > > b= '' xü '' > > > a is bFalse > > > a= '' ü '' > > > b= '' ü '' > > > a is bTrue > > > # strange : with one special character it works as expected | Different storage position of equal strings with special characters |
Python | I 'm trying to use python 's dis library to experiment with & understand performance . Below is an experiment i tried , with the results. > > > dis.dis ( myfunc1 ) > > > dis.dis ( myfunc2 ) Now , i understand that ... the 4 & 5 on the far left are the line numbersthe column in the middle is the opcodes that are called ... | import disdef myfunc1 ( dictionary ) : t = tuple ( dictionary.items ( ) ) return tdef myfunc2 ( dictionary , func=tuple ) : t = func ( dictionary.items ( ) ) return t 4 0 LOAD_GLOBAL 0 ( tuple ) 3 LOAD_FAST 0 ( dictionary ) 6 LOAD_ATTR 1 ( items ) 9 CALL_FUNCTION 0 12 CALL_FUNCTION 1 15 STORE_FAST 1 ( t ) 5 18 LOAD_FAS... | How does one use ` dis.dis ` to analyze performance ? |
Python | I have this list of tuplesThe first value in the tuple is the parent and the second is the value.i want the output to be like this.i can add it to the dictionary but i want it to be nested like a tree with multiple children.Any help is appreciated . | list_of_tuples = [ ( ' 0 ' , ' 1 ' ) , ( ' 1 ' , ' 1.1 ' ) , ( ' 1 ' , ' 1.2 ' ) , ( ' 1 ' , ' 1.3 ' ) , ( ' 1 ' , ' 1.4 ' ) , ( ' 0 ' , ' 3 ' ) , ( ' 3 ' , ' 3.1 ' ) , ( ' 3 ' , ' 3.2 ' ) , ( ' 3 ' , ' 3.3 ' ) , ( ' 3 ' , ' 3.4 ' ) , ( ' 3 ' , ' 3.5 ' ) , ( ' 0 ' , ' 4 ' ) , ( ' 4 ' , ' 4.1 ' ) , ( ' 4 ' , ' 4.2 ' ) ,... | multi nested dictionary from tuples in python |
Python | I 'm just getting into Python and I 'm building a program that analyzes a group of words and returns how many times each letter appears in the text . i.e ' A:10 , B:3 , C:5 ... etc ' . So far it 's working perfectly except that i am looking for a way to condense the code so i 'm not writing out each part of the program... | print ( `` Enter text to be analyzed : `` ) message = input ( ) A = 0b = 0c = 0 ... etcfor letter in message : if letter == `` a '' : a += 1 if letter == `` b '' : b += 1 if letter == `` c '' : c += 1 ... etcprint ( `` A : '' , a , `` B : '' , b , `` C : '' , c ... etc ) | Count number of occurrences of a character in a string |
Python | Consider the following : This runs without problems . As I understand it ( please correct me if I 'm wrong , though ) , the list comprehension expression introduces a new scope , but since it is created within a function ( as opposed to , say , a class ) , it has access to the surrounding scope , including the variable... | def f ( ) : a = 2 b = [ a + i for i in range ( 3 ) ] f ( ) > > > b = [ a + i for i in range ( 3 ) ] Traceback ( most recent call last ) : File `` < string > '' , line 293 , in runcode File `` < interactive input > '' , line 1 , in < module > File `` < interactive input > '' , line 1 , in < listcomp > NameError : global... | List comprehensions : different behaviour with respect to scope in debug mode and in normal runtime |
Python | Edit : I found a working solution , but I would still love more explanation to what 's going on here : Original question : Below we have Matrix M composed of expressions f1 ( x1 , x2 ) and f2 ( x1 , x2 ) . I would like to know the values of x1 and x2 when M = [ f1 , f2 ] = [ 0 , 0 ] .The follow code is working , minus ... | from scipy import optimizefrom sympy import lambdify , DeferredVectorv = DeferredVector ( ' v ' ) f_expr = ( v [ 0 ] ** 2 + v [ 1 ] ** 2 ) f = lambdify ( v , f_expr , 'numpy ' ) zero = optimize.root ( f , x0= [ 0 , 0 ] , method='krylov ' ) zero import numpy as npimport sympy as spimport matplotlib.pyplot as pltfrom sci... | Finding roots with a SymPy Matrix |
Python | The class Item has a member function text ( ) that returns a list of strings.The class Dictionary has a member function items ( ) that returns a list of Items.dict is an instance of Dictionary.I want to test if all characters in all strings in all items in dict are ASCII.I triedThis gives the error message `` global na... | all ( ord ( ch ) < 128 for ch in s for s in item.text ( ) for item in dict.items ( ) ) | Python , iterated list comprehension |
Python | I am developing a collection of Python packages/modules ( no executables ) . What is the correct/best way to set up the file hierarchy for testing . I can think of two scenarios : Scenario 1 : Scenario 2 : I am new to unittesting ( I know I should have done it long ago ) so I 'm not sure which of these approaches is be... | AllPackages/ package1/ module1-1.py module1-2.py package2/ module2-1.py module2-2.py tests/ package1/ test_module1-1.py test_module1-2.py package2/ test_module2-1.py test_module2-2.py AllPackages/ package1/ module1-1.py module1-2.py tests/ test_module1-1.py test_module1-2.py package2/ module2-1.py module2-2.py tests/ t... | Appropriate file hierarchy for unittesting in Python |
Python | I have a dataframe that looks like this : what I 'm trying to achieve is to multiply certain score values corresponding to specific products by a constant.I have the products target of this multiplication in a list like this : [ 1069104 , 1069105 ] ( this is just a simplifiedexample , in reality it would be more than t... | product score0 1179160 0.4246541 1066490 0.4245092 1148126 0.4222073 1069104 0.4204554 1069105 0.414603.. ... ... 491 1160330 0.168784492 1069098 0.168749493 1077784 0.168738494 1193369 0.168703495 1179741 0.168684 product score0 1179160 0.4246541 1066490 0.4245092 1148126 0.4222073 1069104 4.2045504 1069105 4.146030..... | How to multiply certain values of a column by a constant ? |
Python | I 'm sorry for the poor phrasing of the question , but it was the best I could do.I know exactly what I want , but not exactly how to ask for it.Here is the logic demonstrated by an example : Two conditions that take on the values 1 or 0 trigger a signal that also takes on the values 1 or 0 . Condition A triggers the s... | # Settings import numpy as np import pandas as pd import datetime # Data frame with input and desired output i column signal_d df = pd.DataFrame ( { 'condition_A ' : list ( '00001100000110 ' ) , 'condition_B ' : list ( '01110011111000 ' ) , 'signal_d ' : list ( '00001111111110 ' ) } ) colnames = list ( df ) df [ colnam... | How can I vectorize a function that uses lagged values of its own output ? |
Python | I want to declare a base class with an abstract method that has a typed parameter such that implementing classes can specify a more specific type for that parameter , for example : However , mypy understandably complains about this : Is there any way in Python to facilitate such a structure ? | from abc import ABC , abstractmethodclass Job ( ABC ) : passclass EasyJob ( Job ) : passclass HardJob ( Job ) : passclass Worker ( ABC ) : @ abstractmethod def run ( self , job : Job ) - > None : raise NotImplementedError ( ) class EasyWorker ( Worker ) : def run ( self , job : EasyJob ) - > None : passclass HardWorker... | Mypy more specific parameter in subclass |
Python | I am working on problem Contains Duplicate III - LeetCode Given an array of integers , find out whether there are two distinct indices i and j in the array such that the absolute difference between nums [ i ] and nums [ j ] **is at most t and the **absolute difference between i and j is at most k. Example 1 : Example 2... | Input : nums = [ 1,2,3,1 ] , k = 3 , t = 0Output : true Input : nums = [ 1,0,1,1 ] , k = 1 , t = 2Output : true Input : nums = [ 1,5,9,1,5,9 ] , k = 2 , t = 3Output : false class Solution2 : def containsNearbyAlmostDuplicate ( self , nums , k , t ) : if t < 0 : return False lookup = { } for i in range ( len ( nums ) ) ... | Bucket sort to find nearby almost duplicates |
Python | The input : big multipart signed and encrypted email ( ~10MB ) done with openssl.Decrypting the file seems to be fast enough.Getting the decrypted information to verify them is MORE than long . It seems there is some problem in M2Crypto library . If you replace the smime_load_pkcs7_bio call by a file writing the p7s + ... | from M2Crypto import SMIME , X509 , BIO , m2 # read signed and encrypted filewith open ( `` toto.p7m '' , `` r '' ) as p7mFile : p7mBio = BIO.File ( p7mFile ) p7m = SMIME.PKCS7 ( m2.pkcs7_read_bio_der ( p7mBio._ptr ( ) ) , 1 ) s = SMIME.SMIME ( ) # Decrypts.load_key ( 'cnt.key ' , 'cnt.crt ' , callback = lambda x : 'cn... | M2Crypto bad performance to decrypt and verify big email |
Python | I know the canonical way to unpack a tuple is like thisbut noticed that you can unpack a tuple like thisDoes the second method incur any extra cost due to some sort of cast or list construction ? Is there a way to inspect how the python interpreter is dealing with this akin to looking at the assembly from a compiler ? | a , b , c = ( 1 , 2 , 3 ) # or ( a , b , c ) = ( 1 , 2 , 3 ) [ a , b , c ] = ( 1 , 2 , 3 ) | Unpack python tuple with [ ] 's |
Python | I installed Python 2.7 today using : Then I keep getting something like `` [ 37745 refs ] '' on screen after each function call : What does those numbers mean ? Anything wrong here and can I get rid of them ? uname -a result : | ./configure -- prefix=/home/zhanwu/local -- enable-shared -- enable-profiling -- with-pydebugmake install [ zhanwu @ cluster ~ ] $ ~/local/bin/pythonPython 2.7.1 ( r271:86832 , Jun 16 2011 , 17:45:05 ) [ GCC 4.1.2 20080704 ( Red Hat 4.1.2-44 ) ] on linux2Type `` help '' , `` copyright '' , `` credits '' or `` license '... | Unknown screen output of manually installed Python 2.7 |
Python | I 'm looking for a way to get all the string splits combinations from a sentence . For example , for the input sentance : `` I am eating pizza '' I would like to get this output : I ca n't find the recursive way of doing this ! Do you have any idea ? This is NOT a duplicate : I am not looking for the whole combinations... | [ [ `` I '' , `` am '' , `` eating '' , `` pizza '' ] , [ `` I '' , `` am eating '' , `` pizza '' ] , [ `` I '' , `` am '' , `` eating pizza '' ] , [ `` I '' , `` am eating pizza '' ] , [ `` I am '' , `` eating '' , `` pizza '' ] , [ `` I am '' , `` eating pizza '' ] , [ `` I am eating '' , `` pizza '' ] , [ `` I am ea... | Find all string split combinations |
Python | asyncio has StreamReader.readline ( ) , allowing something like : ( I do n't see async for available in asyncio but that would be the obvious evolution ) How do I achieve the equivalent with trio ? I do n't see any high level support for this directly in trio 0.9 . All I see is ReceiveStream.receive_some ( ) which retu... | while True : line = await reader.readline ( ) ... | How can I read one line at a time from a trio ReceiveStream ? |
Python | I 'm defining a table in SQLAlchemy using the declarative API . It 's got a foreign key which I 'd like to index . My question is : how do I define the index created from master_ref to be an ASC or DESC index ( without resorting to doing it manually with SQL ) ? Looking at the documentation of SqlAlchemy , an alternati... | class Item ( Base ) : id = Column ( INTEGER , primary_key=True ) master_ref = Column ( INTEGER , ForeignKey ( 'master.id ' ) , nullable=True , index=True ) value = Column ( REAL ) class Item ( Base ) : id = Column ( INTEGER , primary_key=True ) master_ref = Column ( INTEGER , ForeignKey ( 'master.id ' ) ) value = Colum... | Create an ordered Index in sqlite db using SQLAlchemy |
Python | This is n't as much of a problem as a curiosity . In my interpreter on 64 bit linux I can executeGreat , just what I would expect.However I found this weird property of the numpy.core.numeric moduleWeird why is numpy.int64 in there twice ? Lets investigate.Whoah they are different . What is going on here ? Why are ther... | In [ 10 ] : np.int64 == np.int64Out [ 10 ] : TrueIn [ 11 ] : np.int64 is np.int64Out [ 11 ] : True In [ 19 ] : from numpy.core.numeric import _typelessdataIn [ 20 ] : _typelessdataOut [ 20 ] : [ numpy.int64 , numpy.float64 , numpy.complex128 , numpy.int64 ] In [ 23 ] : _typelessdata [ 0 ] is _typelessdata [ -1 ] Out [ ... | Why are there two np.int64s in numpy.core.numeric._typelessdata ( Why is numpy.int64 not numpy.int64 ? ) |
Python | I have a list , which is made up of the following elements , Where each element of this list can itself be a variable size list , eg , It 's straight forward for me to set up a generator that loops through list1 , and yields the constituents of each element ; However , is there a way of doing this so I can specify the ... | list1 = [ a1 , a2 , a3 ] a1 = [ x1 , y1 , z1 ] , a2 = [ w2 , x2 , y2 , z2 ] , a3 = [ p3 , r3 , t3 , n3 ] array = [ ] for i in list1 : for j in i : array.append [ j ] yield array 1st yield : [ x1 , y1 ] 2nd yield : [ z1 , w1 ] 3rd yield : [ x2 , y2 ] 4th yield : [ z2 , p3 ] 5th yield : [ r3 , t3 ] 6th yield : [ n3 ] 7th... | Dynamically generating elements of list within list |
Python | output and error message : I am wondering how the python interpreter works . Note that x=3 does n't run at all , and it should n't be treated as a local variable , which means the error would be `` name ' x ' is not defined '' . But look into the code and the error message , it is n't the case . Could anybody explain t... | def fun ( ) : if False : x=3 print ( locals ( ) ) print ( x ) fun ( ) { } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -UnboundLocalError Traceback ( most recent call last ) < ipython-input-57-d9deb3063ae1 > in < module > ( ) 4 print ( locals ( ) ) 5 pri... | Python local variable compile principle |
Python | Does python garbage collector cleans up a compound object if some of its parts are still referencede.g.Will A [ 0 ] be garbage collected ? Is there a way to confirm the same through code ? | def foo ( ) : A = [ [ 1 , 3 , 5 , 7 ] , [ 2 , 4 , 6 , 8 ] ] return A [ 1 ] B = foo ( ) | python garbage collector behavior on compound objects |
Python | I am new to keras and deep learnin.When i crate a sample basic model , i fit it and my model 's log loss is same always.Train on 17939 samples , validate on 4485 samplesEpoch 1/20017939/17939 [ ============================== ] - 8s - loss : 99.8137 - acc : 0.3096 - val_loss : 99.9626 - val_acc : 0.0000e+00Epoch 2/20017... | model = Sequential ( ) model.add ( Convolution2D ( 32 , 3 , 3 , border_mode='same ' , init='he_normal ' , input_shape= ( color_type , img_rows , img_cols ) ) ) model.add ( MaxPooling2D ( pool_size= ( 2 , 2 ) , dim_ordering= '' th '' ) ) model.add ( Dropout ( 0.5 ) ) model.add ( Convolution2D ( 64 , 3 , 3 , border_mode=... | Keras log_loss error is same |
Python | I am looking for a way to enumerate all possible two-member group constellations for n members.E.g. , for n = 4 members the following 3 unique group constellations are possible ( please note that neither the order of the members within a group nor the group order is of importance ) : E.g. , for n = 6 members the 15 uni... | ( ( 1,2 ) , ( 3,4 ) ) ( ( 1,3 ) , ( 2,4 ) ) ( ( 1,4 ) , ( 2,3 ) ) ( ( 1,2 ) , ( 3,4 ) , ( 5,6 ) ) ( ( 1,2 ) , ( 5,4 ) , ( 3,6 ) ) ( ( 1,2 ) , ( 6,4 ) , ( 5,3 ) ) ( ( 1,3 ) , ( 2,4 ) , ( 5,6 ) ) ( ( 1,3 ) , ( 2,6 ) , ( 5,4 ) ) ( ( 1,3 ) , ( 2,5 ) , ( 4,6 ) ) ( ( 1,4 ) , ( 3,2 ) , ( 5,6 ) ) ( ( 1,4 ) , ( 3,5 ) , ( 2,6 ) ... | Enumeration of all possible two-member group constellations |
Python | I was surprised that the deep learning algorithms I had implemented did not work , and I decided to create a very simple example , to understand the functioning of CNN better . Here is my attempt of constructing a small CNN for a very simple task , which provides unexpected results.I have implemented a simple CNN with ... | # Parameterssize_image = 256normalization = 1 sigma = 7n_train = 4900ind_samples_training =np.linspace ( 1 , n_train , n_train ) .astype ( int ) nb_epochs = 5minibatch_size = 5learning_rate = np.logspace ( -3 , -5 , nb_epochs ) tf.reset_default_graph ( ) tf.set_random_seed ( 1 ) seed = 3 n_train = len ( ind_samples_tra... | Why my one-filter convolutional neural network is unable to learn a simple gaussian kernel ? |
Python | This is an example of my exception handling in a django project : There is only two excepts now , but it should be more for the several request exceptions . But already the view method is bloated up by this . Is there a way to forward the except handling to a separate error method ? There is also the problem , that I n... | def boxinfo ( request , url : str ) : box = get_box ( url ) try : box.connect ( ) except requests.exceptions.ConnectionError as e : context = { 'error_message ' : 'Could not connect to your box because the host is unknown . ' } return render ( request , 'box/error.html ' , context ) except requests.exceptions.RequestEx... | how to improve exception handling in python/django |
Python | I have a boolean ( numpy ) array . And I want to count how many occurrences of 'True ' are between the Falses . Eg for a sample list : should produce my initial attempt was to try this snippet : But it keeps appending elements in ml for each F in the b_List.EDITThank you all for your answers . Sadly I can ' accept all ... | b_List = [ T , T , T , F , F , F , F , T , T , T , F , F , T , F ] ml = [ 3,3,1 ] i = 0ml = [ ] for el in b_List : if ( b_List ) : i += 1 ml.append ( i ) i = 0 | Count the number of occurrences between markers in a python list |
Python | I 'm reading a valid JSON file ( nested 5 levels deep ) , then adding some data to it , and subsequently trying to use that data for some calculations . I 'm getting int is not subscriptable errors in a random fashion . I ca n't wrap my head around it . casting to str ( ) does n't help , printing with pprint does n't a... | with open ( rNgram_file , ' r ' , encoding='utf-8 ' ) as ngram_file : data = json.load ( ngram_file ) data = rank_items ( data ) data = probability_items ( data ) for ngram , one_grams in data.items ( ) : ngram_rank = 0 for one_gram , two_grams in one_grams.items ( ) : one_gram_rank = 0 [ .. ] for four_gram , values in... | Random `` int is not subscriptable '' behaviour |
Python | I just came across this here , always used like this : What does the < > operator do , and why not use the usual == or in ? Sorry if that has been answered before , search engines do n't like punctuation . | if string1.find ( string2 ) < > -1 : pass | What does the < > operator do in python ? |
Python | I have some old programs from back in the times when python 3.1 came out . In the program I often used the Callable ( ) to pass a function and it 's parameters like this to my TKinter application : Now I wanted to use my programs again but the callable- Object was gone . In the web I found that this functionality was r... | tvf.mi ( datei_bu , text=datei_opt , command=Callable ( exec_datei_opts , datei_opt ) ) | On Raspbian run multiple python Versions simultaniously |
Python | When I start any application , that I wrote with python for my Nokia 5800 ( software version 60.0.003 ) , it asks me for internet connection . Application does n't use it or need it . And if I skip it applications works fine.I 'm using ensymble ( PyS60 application packager 2.0.0 ) with Python 2.5.2 to create applicatio... | print `` Hello world ! '' | Application asks for internet connection |
Python | Coming from a Perl background , I 'm used to something like : I 'm wondering if the following Python incurs a run-time performance hit : or if words is bound at compile-time . | my @ words = qw ( fee fi fo fum ) ; words = 'fee fi fo fum'.split ( ) | Is split ( ) of a static string a run-time or compile-time operation ? |
Python | Im trying to execute a .py program from within my python code , but non-ASCII characters behave oddly when printed and dealt with.module1.py : Main code : I want this to print áéíóúabcdefgçë but it instead prints áéÃóúabcdefgçà « . This happens with all non-ASCII characters i have tried.I am using Python 3.7 and ... | test = `` áéíóúabcdefgçë '' print ( test ) exec ( open ( `` module1.py '' ) .read ( ) , globals ( ) ) | exec ( ) not working with unicode characters |
Python | I have a dozen or so permission lookups on views that make sure users have the right permissions to do something on the system ( ie make sure they 're in the right group , if they can edit their profile , if they 're group administrators , etc ) .A check might look like this : This is actually code from the Django tuto... | from django.contrib.auth.decorators import user_passes_testtest_canvote = lambda u : u.has_perm ( 'polls.can_vote ' ) @ user_passes_test ( test_canvote ) def my_view ( request ) : # ... @ cached_user_passes_test ( 'test_canvote ' ) def my_view ( request ) : # ... try : from functools import update_wrapper , wrapsexcept... | Caching non-view returns |
Python | I have deployed a fastapi endpoint , I can request output from the API endpoint and its working fine for me perfectly.Now , the biggest challenge for me to know how much time it is taking for each iteration . Because in the UI part ( those who are accessing my API endpoint ) I want to help them show a progress bar ( TI... | from fastapi import FastAPI , UploadFilefrom typing import Listapp = FastAPI ( ) @ app.post ( '/work/test ' ) async def testing ( files : List ( UploadFile ) ) : for i in files : ... ... . # do a lot of operations on each file # after than I am just writing that processed data into mysql database # cur.execute ( ... ) ... | How to send a progress of operation in a FastAPI app ? |
Python | let 's say I have a listWhat is the most efficient way to return the count of unique `` codes '' in this list ? In this case , the unique codes is 2 , because only 2B and 2A are unique.I could put everything in a list and compare , but is this really efficient ? | li = [ { ' q ' : 'apple ' , 'code ' : '2B ' } , { ' q ' : 'orange ' , 'code ' : '2A ' } , { ' q ' : 'plum ' , 'code ' : '2A ' } ] | How do I most efficienty check the unique elements in a list ? |
Python | I am trying to write a piece of code that will go through a list of numbers ( splitting on vertical bars ) that if the user enters a non number , will throw an exception and replace said object with 0 . It is intended to display the list in descending order ( largest to smallest ) with vertical bars in between.This is ... | numbers = input ( `` Please enter several integer numbers separated by vertical bars . `` ) .split ( '| ' ) for item in numbers : try : numbers = [ int ( item ) for item in numbers ] except ValueError : item = item.replace ( item , ' 0 ' ) numbers = sorted ( numbers , reverse = True ) print ( ' | '.join ( str ( num ) f... | How make a `` ValueError '' exception replace an item in a list |
Python | Let 's say , I have a bunch of functions a , b , c , d and e and I want to find out if they call any method from the random module : I want to write a function uses_module so I can expect these assertions to pass : ( uses_module ( b ) is False because random is only imported but never one of its methods called . ) I ca... | def a ( ) : passdef b ( ) : import randomdef c ( ) : import random random.randint ( 0 , 1 ) def d ( ) : import random as ra ra.randint ( 0 , 1 ) def e ( ) : from random import randint as ra ra ( 0 , 1 ) assert uses_module ( a ) == Falseassert uses_module ( b ) == Falseassert uses_module ( c ) == Trueassert uses_module ... | How to find out if ( the source code of ) a function contains a call to a method from a specific module ? |
Python | Here is an example : How can I tell dict ( ) constructor to use Unicode instead without writing the string literal expliclity like u ' a ' ? I am loading a dictionary from a json module which defaults to use unicode . I want to make use of unicode from now on . | d = dict ( a = 2 ) print d { ' a ' : 2 } | How do I tell dict ( ) in Python 2 to use unicode instead of byte string ? |
Python | As a relative new-comer to Python I am trying to use the sklearn RandomForestClassifier . One example from a how-to guide by yhat is the following : Can some explain what the y , _ assignment does and how it works . It is n't used explicitly , but I get an error if I leave it out . | from sklearn.datasets import load_irisfrom sklearn.ensemble import RandomForestClassifierimport pandas as pdimport numpy as npiris = load_iris ( ) df = pd.DataFrame ( iris.data , columns=iris.feature_names ) df [ 'is_train ' ] = np.random.uniform ( 0 , 1 , len ( df ) ) < = .75df [ 'species ' ] = pd.Factor ( iris.target... | What does y , _ assignment do in python / sklearn ? |
Python | I have some python code that parse the csv file . Now our vendor decide to change the data file to gzip csv file . I was wondering what 's the minimal/cleanest code change I have to make . Current function : I do n't want to duplicate the code to load_data2 ( ) , and change the with statement to , thought it works perf... | def load_data ( fname , cols= ( ) ) : ... ... with open ( fname ) as f : reader = csv.DictReader ( f ) ... ... with gzip.open ( fname ) as f : def load_data ( fname , cols= ( ) ) : ... ... if fname.endswith ( '.csv.gz ' ) : with gzip.open ( fname ) as f : else : with open ( fname ) as f : reader = csv.DictReader ( f ) ... | Python `` with '' statement syntax |
Python | I 'm wondering about some details of how for ... in works in Python.My understanding is for var in iterable on each iteration creates a variable , var , bound to the current value of iterable . So , if you do for c in cows ; c = cows [ whatever ] , but changing c within the loop does not affect the original value . How... | cows= [ 0,1,2,3,4,5 ] for c in cows : c+=2 # cows is now the same - [ 0,1,2,3,4,5 ] cows= [ { 'cow':0 } , { 'cow':1 } , { 'cow':2 } , { 'cow':3 } , { 'cow':4 } , { 'cow':5 } ] for c in cows : c [ 'cow ' ] +=2 # cows is now [ { 'cow ' : 2 } , { 'cow ' : 3 } , { 'cow ' : 4 } , { 'cow ' : 5 } , { 'cow ' : 6 } , { 'cow ' :... | Why does Python 's 'for ... in ' work differently on a list of values vs. a list of dictionaries ? |
Python | I 'm surprised that And while we are at it , also thatI did n't find any other examples . Is there a reason or some logic I 've missed that makes this the right choice ? Or is this a slip ? I was expecting nan . As for every other number except 1 or 0j.Edit 1 : Thanks to jedwards 's comment below I have a reference . B... | > > > import math > > > 1**math.nan1.0 > > > 0j**math.nan0j | A surprise with 1**math.nan and 0j**math.nan |
Python | I 'm trying to run a pyomo optimization and I get the error message [ Error 6 ] The handle is invalid . Not sure how to interpret it , looking around it seems to have something to do with privileges but I do n't really understand it.Find below the complete error trace and also a toy example to reproduce it . Full error... | from pyomo.environ import *infinity = float ( 'inf ' ) model = AbstractModel ( ) # Foodsmodel.F = Set ( ) # Nutrientsmodel.N = Set ( ) # Cost of each foodmodel.c = Param ( model.F , within=PositiveReals ) # Amount of nutrient in each foodmodel.a = Param ( model.F , model.N , within=NonNegativeReals ) # Lower and upper ... | pyomo + reticulate error 6 the handle is invalid |
Python | This code prints a different string between Windows and Linux.test.py : Platform : x86_64 Linux 4.4 .0-17763 - MicrosoftPython version : 3.7.2Terminals : bash , fish Abbreviated output : Platform : Windows 10 1809Python version : 3.6.8 , 3.7.0 , 3.7.2Terminals : cmd , powershellAbbreviated output : So why , in Windows ... | print ( `` ; '' .join ( [ str ( i ) for i in range ( 10000 ) ] ) ) $ python -- versionPython 3.7.2 $ python test.py0 ; 1 ; 2 ; 3 ; 4 ; 5 ; 6 ... .9997 ; 9998 ; 9999 $ python -u test.py0 ; 1 ; 2 ; 3 ; 4 ; 5 ; 6 ... .9997 ; 9998 ; 9999 ./python -- versionPython 3.6.8./python test.py0 ; 1 ; 2 ; 3 ; 4 ; 5 ; 6 ... .9997 ; 9... | Why does this code print a different result between Windows and Linux ? |
Python | I 'm trying to write an algorithm ( which I 'm assuming will rely on natural language processing techniques ) to 'fill out ' a list of search terms . There is probably a name for this kind of thing which I 'm unaware of . What is this kind of problem called , and what kind of algorithm will give me the following behavi... | docs = [ `` I bought a ticket to the Dolphin Watching cruise '' , `` I enjoyed the Dolphin Watching tour '' , `` The Miami Dolphins lost again ! `` , `` It was good going to that Miami Dolphins game '' ] , search_term = `` Dolphin '' [ `` Dolphin Watching '' , `` Miami Dolphins '' ] | NLP algorithm to 'fill out ' search terms |
Python | And for reference sake - args is : for this query to work i need to reference args as because if I useI get the error : int ( ) argument must be a string , a bytes-like object or a number , not 'tuple ' I understand that it thinks it 's a tuple even though it 's only one value but when I do the following in terminalI g... | def test_stats ( team , *args ) : if not args : [ do some stuff ] else : team_fixtures = ( Fixtures.objects.filter ( home_team=team_details.id ) | Fixtures.objects.filter ( away_team=team_details.id ) ) /.filter ( fixture_datetime__lt=datetime.now ( ) ) .filter ( fixture_datetime__year=args [ 0 ] ) date_year = datetime... | python args not working unless it has a position reference |
Python | I 'm not entirely sure this is for stackoverflow , so please correct me if not.i.e . say we have t.py with contents : And now we execute it : $ python3 t.pyFrom the docs : A class definition is an executable statement . It first evaluates the inheritance list , if present . Each item in the inheritance list should eval... | class A ( object ) : passprint ( `` A : '' , A ) class B ( object ) : print ( `` From B : A : '' , A ) class OuterClass ( object ) : class AA ( object ) : pass print ( `` AA : '' , AA ) class BB ( object ) : print ( `` From BB : AA : '' , AA ) A : < class '__main__.A ' > From B : A : < class '__main__.A ' > AA : < clas... | Why does n't `` class '' start a new scope like `` def '' does ? |
Python | the locale/django.po file has 7868 lines . Sometimes the makemessages command works and sometimes it throws this error : Its strange because in the error is always a different line of django.pot mentioned.And do n't forget that it sometimes works with the same code , so the code should be fine | manage.py makemessages -l deCommandError : errors happened while running msguniq/app/xxx/locale/django.pot:1871 : /app/xxx/locale/django.pot : input is not valid in `` ASCII '' encoding | Django Makemessages CommandError ASCII Encoding |
Python | Everybody loves Python 3.6 's new f-strings : However , while functionally very similar , they do n't have the exact same semantics as str.format ( ) : In particular , str.format ( ) handles getitem syntax very differently : Given the ability to handle full-blown python expression syntax , f-strings are wonderful and I... | In [ 33 ] : foo = { 'blah ' : 'bang ' } In [ 34 ] : bar = 'blah'In [ 35 ] : f ' { foo [ bar ] } 'Out [ 35 ] : 'bang ' In [ 36 ] : ' { foo [ bar ] } '.format ( **locals ( ) ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -KeyError Traceback ( most recent c... | Is there a callable equivalent to f-string syntax ? |
Python | Using TastyPie I have a model resource which has a FK user . When I make a POST to the API I have to include the user id like this : My users have to authenticate either by logging in or using an API Key and username and password . In both cases I already know who the user is . 1 ) How can I make user sure that user1 d... | data : JSON.stringify ( { name : 'value a ' , user : '12 ' } ) , | Model resource with users as FK TastyPie API |
Python | Suppose I have function , f , which takes in some variable and returns a variable of the same type . For simplicity , let 's sayI 'm interested in applying f to itself over and over . Something like f ( f ( f ( ... ( f ( x ) ) ... ) ) ) .I could do this likeBut I was wondering if there was a simpler , less verbose way ... | def f ( x ) : return x/2+1 s = f ( x ) for i in range ( 100 ) : s = f ( s ) | How can I apply a function to itself ? |
Python | I have a class which makes requests to a remote API . I 'd like to be able to reduce the number of calls I 'm making . Some of the methods in my class make the same API calls ( but for different reasons ) , so I'ld like the ability for them to 'share ' a cached API response.I 'm not entirely sure if it 's more Pythonic... | class A : def a_method ( item_id , cached_item_api_response = None ) : `` '' '' Seems awkward having to supplied item_id even if cached_item_api_response is given `` '' '' api_response = None if cached_item_api_response : api_response = cached_item_api_response else : api_response = ... # make api call using item_id ..... | Python - Better to have multiple methods or lots of optional parameters ? |
Python | I have the following code : which results into a Error : What is the proper way to define this function ? I need sympy for this because I plan to integrate it later . | l = 2h = 1p = 2q = -2x = Symbol ( ' x ' ) f = Piecewise ( ( 0 , x < 0 ) , ( p , 0 < = x < = l/3 ) , ( h/l * x - h , l/3 < x < 2*l/3 ) , ( q , 2*l/3 < = x < = l ) , ( 0 , x > l ) ) TypeError : can not determine truth value of Relational | How to define a piecewise function without `` TypeError : can not determine truth value '' |
Python | I 'm having problems with some code that loops through a bunch of .csvs and deletes the final line if there 's nothing in it ( i.e . files that end with the \n newline character ) My code works successfully on all files except one , which is the largest file in the directory at 11gb . The second largest file is 4.5gb.T... | with open ( path_str , '' r+ '' ) as my_file : IOError : [ Errno 22 ] invalid mode ( ' r+ ' ) or filename : ' F : \\Shapefiles\\ab_premium\\processed_csvs\\a.csv ' with open ( path_str , '' r '' ) as my_file : | Python fails to open 11gb csv in r+ mode but opens in r mode |
Python | I tried to look for the solution and I am unable to get 1 . I have the following output from an api in python.I want the data frame something like thisWhen I use the following I get the followingHow do I move ahead with this ? | insights = [ < Insights > { `` account_id '' : `` 1234 '' , `` actions '' : [ { `` action_type '' : `` add_to_cart '' , `` value '' : `` 8 '' } , { `` action_type '' : `` purchase '' , `` value '' : `` 2 '' } ] , `` cust_id '' : `` xyz123 '' , `` cust_name '' : `` xyz '' , } , < Insights > { `` account_id '' : `` 1234 ... | Convert list of dictionaries containing another list of dictionaries to dataframe |
Python | ... and every for-loop looked like a list comprehension . Instead of : I was doing ( not assigning the list to anything ) : This is a common pattern found on list-comp how-to 's . 1 ) OK , so no big deal right ? Wrong . 2 ) Ca n't this just be code style ? Super wrong.1 ) Yea that was wrong . As NiklasB points out , th... | for stuff in all_stuff : do ( stuff ) [ do ( stuff ) for stuff in all_stuff ] | I found myself swinging the list comprehension hammer |
Python | PyLint told me that one of my class methods did n't need to be a method , but could just be a function in a class since it did n't use any class attribute . That made me do things I thought were `` bad , '' but maybe they are Pythonic . Is the following code what Python wants us to do ? where ParentClass.event emits te... | class TestClass ( ParentClass ) : def __init__ ( self ) : def callbackfunction ( text ) : print ( `` hello '' ) ParentClass.map_event_to_callback ( ParentClass.event , callbackfunction ) class TestClass ( ) : def __init__ ( self , text ) : def printhello ( text ) : print ( `` hello '' ) printhello ( text ) | Is it un-pythonic to define a function inside of a class method ? |
Python | Suppose I havewhere distance2 ( vector1 , vector2 ) finds the ( squared ) Euclidian distance between vector1 and vector2 . The function will work for iterable elements , but suppose we also want to make it work for non-iterable elements ( i.e . distance2 ( 1,3 ) ) . Is there a pythonic way to do this ? ( i.e , automati... | def distance2 ( vector1 , vector2 ) : zipped = zip ( vector1 , vector2 ) difference2 = [ ( vector2 - vector1 ) ** 2 for ( vector1 , vector2 ) in zipped ] return sum ( difference2 ) | Pythonic conversion to singleton iterable if not already an iterable |
Python | I have this data structure where each team has list of issues with start/end dates . For each team , I would like to merge issues with same key and overlapping dates , where in result issue the start date will be smaller date and end date will be bigger date.I am trying to do it with few for loops but I was wondering w... | { 'Team A ' : [ { 'start ' : '11/Jul/13 1:49 PM ' , 'end ' : '10/Oct/13 5:16 PM ' , 'issue ' : 'KEY-12678 ' } , { 'start ' : ' 3/Oct/13 10:40 AM ' , 'end ' : '11/Nov/13 1:02 PM ' , 'issue ' : 'KEY-12678 ' } ] , 'Team B ' : [ { 'start ' : ' 5/Sep/13 3:35 PM ' , 'end ' : '08/Nov/13 3:35 PM ' , 'issue ' : 'KEY-12679 ' } ,... | Pythonic way to filter data with overlapping dates |
Python | If I have a list of objects , I can use the __cmp__ method to override objects are compared . This affects how the == operator works , and the item in list function . However , it does n't seem to affect the item in set function - I 'm wondering how I can change the MyClass object so that I can override the behaviour h... | class MyClass ( object ) : def __init__ ( self , s ) : self.s = s def __cmp__ ( self , other ) : return cmp ( self.s , other.s ) instance1 , instance2 = MyClass ( `` a '' ) , MyClass ( `` a '' ) print instance2==instance1 # Trueprint instance2 in [ instance1 ] # Trueprint instance2 in set ( [ instance1 ] ) # False | In python - the operator which a set uses for test if an object is in the set |
Python | I 'm playing with slices in Python ( 2.7.4 ) : Everything seems to work as expected : Except it seems that the slice indices are limited to 0x7FFFFFFF : Why are slice indices not subject to the same long integer promotion as regular int values ? Is there any workaround for this ? | class Foo ( ) : def __getitem__ ( self , key ) : # Single value if isinstance ( key , ( int , long ) ) : return key # Slice if isinstance ( key , slice ) : print 'key.start = 0x { 0 : X } key.stop = 0x { 1 : X } '.format ( key.start , key.stop ) length = key.stop - key.start return str ( length ) > > > f = Foo ( ) > > ... | Slice indices limited to 0x7FFFFFFF |
Python | I 'd like to do something like : to get : but of course python dies when you enter an argument which is not a script or goes into non interactive mode if you do.Can I do this somehow ? | % python foo barimport syssys.argv % [ 'foo ' , 'bar ' ] | Can I access sys.argv in python in interactive mode ? |
Python | Is there any way to make this work without for loops ? I 've tried calling function ( x [ None , : ] , y [ : , None ] ) , where : but it requires list .any or .all methods . I 'm looking for specifically functionless method ( without fromfunction and vectorization ) .Big thanks ! | import import numpy as npimport matplotlib.pyplot as plt L = 1N = 255dh = 2*L/Ndh2 = dh*dhphi_0 = 1c = int ( N/2 ) r_0 = L/2arr = np.empty ( ( N , N ) ) for i in range ( N ) : for j in range ( N ) : arr [ i , j ] = phi_0 if ( i - c ) **2 + ( j - c ) **2 < r_0**2/dh2 else 0plt.imshow ( arr ) function ( i , j ) : return ... | NumPy - Vectorizing loops involving range iterators |
Python | Python classes have no concept of public/private , so we are told to not touch something that starts with an underscore unless we created it . But does this not require complete knowledge of all classes from which we inherit , directly or indirectly ? Witness : Expectedly , a TypeError is raised when None + 1 is evalua... | class Base ( object ) : def __init__ ( self ) : super ( Base , self ) .__init__ ( ) self._foo = 0 def foo ( self ) : return self._foo + 1class Sub ( Base ) : def __init__ ( self ) : super ( Sub , self ) .__init__ ( ) self._foo = NoneSub ( ) .foo ( ) class Sub ( object ) : def __init__ ( self ) : self.__foo = 12 def foo... | Does Python require intimate knowledge of all classes in the inheritance chain ? |
Python | I 'm experimenting with z3 in python . I have the following model : I can load it and check that is sat . At this point how can I get an example value for a and another ? Thanks | ( set-option : produce-models true ) ( set-logic QF_AUFBV ) ( declare-fun a ( ) ( Array ( _ BitVec 32 ) ( _ BitVec 8 ) ) ) ( declare-fun another ( ) ( Array ( _ BitVec 32 ) ( _ BitVec 8 ) ) ) ( assert ( and ( = false ( = ( _ bv77 32 ) ( concat ( select a ( _ bv3 32 ) ) ( concat ( select a ( _ bv2 32 ) ) ( concat ( sele... | How get a a value from a Lambda expression ? |
Python | I 'm currently going through the Lynda Python tutorial and in the section on generators I see the following code : I did n't catch it at first , but as I was going through the code I noticed that the else keyword had an entire for-loop between it and an if at the same indentation level . To my surprise , the code not o... | def isprime ( n ) : if n == 1 : return False for x in range ( 2 , n ) : if n % x == 0 : return False else : return True def isprime ( n ) : if n == 1 : return False for x in range ( 2 , n ) : if n % x == 0 : return False return True | Python : for loop between if-else , how/why does this work ? |
Python | My goal is to change a word in a sentence and write into a text file.I created a text file : I have got this example sentence : `` I have got a RED cat '' I want to change the `` RED '' , the colour name , and write ( append ) every sentence to my data.txt.How can I take it into a loop , replace only this part and writ... | filename = `` /Users/Adam/Desktop/data.txt '' text = open ( filename , ' r ' ) lines = text.readlines ( ) colours= { red , blue , yellow , green , etc.. } # ! /usr/bin/python # ! /bin/sh # -*- coding : utf-8 -*-from bs4 import BeautifulSoupfrom selenium import webdriverimport urllib2import subprocessimport unicodecsv a... | Replace one part text element in a for loop Python |
Python | I have a large dataset of CSV files comprised of two distinct objects : object_a and object_b . Each of these entities has a numeric tick value as well.Each object shares a Parent Name value so in most cases , one of each object will share a Parent Name value but this is not always the case.I have two objectives with t... | Type , Parent Name , Ticksobject_a , 4556421 , 34object_a , 4556421 , 0object_b , 4556421 , 0object_a , 3217863 , 2object_b , 3217863 , 1 ... ... def objective_one ( group_name , group_df ) : group_df = group_df [ group_df [ 'Type ' ] == 'object_a ' ] if len ( group_df ) > 1 : zero_tick_object_a = group_df [ group_df [... | Faster way to accomplish this Pandas job than by using Apply for large data set ? |
Python | I 'm trying my hand at converting the following loop to a comprehension.Problem is given an input_list = [ 1 , 2 , 3 , 4 , 5 ] return a list with each element as multiple of all elements till that index starting from left to right.Hence return list would be [ 1 , 2 , 6 , 24 , 120 ] .The normal loop I have ( and it 's w... | l2r = list ( ) for i in range ( lst_len ) : if i == 0 : l2r.append ( lst_num [ i ] ) else : l2r.append ( lst_num [ i ] * l2r [ i-1 ] ) | How to calculate a cumulative product of a list using list comprehension |
Python | I am trying to install BeautifulSoup4 using the command pip install BeautifulSoup4 , as per the bs documentation here : https : //www.crummy.com/software/BeautifulSoup/ # DownloadI am using Mac OS X 10.7.5 , and python 2.7.12When I run the command in Terminal I get the error : Can anyone suggest what I 'm doing wrong ?... | AttributeError : '_socketobject ' object has no attribute 'set_tlsext_host_name ' | pip install bs4 giving _socketobject error |
Python | Assuming that I have 3 different dictionaries : I want to compute the product of these dictionaries ( excluding the product between dict2 and dict3 ) and combine both the keys and values where the keys are concatenated with _ and values with ' and 'The desired output would be a single dictionary : I had a look at the d... | dict1 = { `` A '' : `` a '' } dict2 = { `` B '' : `` b '' , `` C '' : `` c '' , `` D '' : `` d '' , `` E '' : `` e '' } dict3 = { `` F '' : `` f '' , `` G '' : `` g '' } { # dict1 x dict2 `` A_B '' : `` a and b '' , `` A_C '' : `` a and c '' , `` A_D '' : `` a and d '' , `` A_E '' : `` a and e '' , # dict1 x dict3 `` A... | Compute the product of 3 dictionaries and concatenate keys and values |
Python | My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.The function should look like this when operating : Usually a function like this would be easy to create when using lists and list methods . But trying to do so without using them is a nightmare.... | > > > sum_numbers ( '34 3 542 11 ' ) 590 > > > def sum_numbers ( s ) : for i in range ( len ( s ) ) : int ( i ) total = s [ i ] + s [ i ] return total > > > sum_numbers ( ' 1 2 3 ' ) '11 ' > > > def sum_numbers ( s ) : for i in range ( len ( s ) ) : map ( int , s [ i ] ) total = s [ i ] + s [ i ] return total > > > sum... | How to convert numbers in a string without using lists ? |
Python | I have a DataFrame I simply want to sum all columns to get a new dataframeWith the columnwise sums And then print it with to_csv ( ) . When is use | A B C D2015-07-18 4.534390e+05 2.990611e+05 5.706540e+05 4.554383e+05 2015-07-22 3.991351e+05 2.606576e+05 3.876394e+05 4.019723e+05 2015-08-07 1.085791e+05 8.215599e+04 1.356295e+05 1.096541e+05 2015-08-19 1.397305e+06 8.681048e+05 1.672141e+06 1.403100e+06 ... A B C Dsum s s s s df.sum ( axis=0 ) print ( df ) A 9.099... | Summing columns to form a new dataframe |
Python | How do I call a function and only pass it the arguments that it expects . For example say I have the following functions : I want some Python code that is able to successfully call these functions without raising a TypeError by passing unexpected arguments . i.e.I 'm not interested in just adding **kwargs to the functi... | func1 = lambda a : Truefunc2 = lambda a , b : Truefunc3 = lambda c : True kwargs = dict ( a=1 , b=2 , c=3 ) for func in ( func1 , func2 , func3 ) : func ( **kwargs ) # some magic here | Call a function in Python and pass only the arguments it expects |
Python | I see someone 's code this way : I can understand the first line -- adding new attributes to the ParentClass ' attribute dictionary . But what is del self.self ? I tried to see what self.self is.It is exactly THAT self . Why should one delete the object in its __init__ function ? When I stepped out __init__ , I found t... | class SomeClass ( ParentClass ) : def __init__ ( self , attribute_1 , attribute_2 ) : self.__dict__.update ( locals ( ) ) del self.self selfOut [ 2 ] : < classname at 0x244ee3f6a90 > self.selfOut [ 3 ] : < classname at 0x244ee3f6a90 > self.self.selfOut [ 4 ] : < classname at 0x244ee3f6a90 > | What does 'del self.self ' in an __init__ function mean ? |
Python | Can somebody explain this tricky output : What happens there ? And why this happens ? Answer : When I asked question I treated not as a function , but actually not is n't a function . That 's why not ( # something ) does n't change operator precedence . For example : is the same as : and : not type ( 1.01 ) == type ( 1... | > > > not ( type ( 1.01 ) ) == type ( 1 ) # Why does the expression evaluates to True ! ? True > > > not ( type ( 1.01 ) ) False > > > False == type ( 1 ) False not ( type ( 1.01 ) ) == type ( 1 ) not ( type ( 1.01 ) == type ( 1 ) ) ( not type ( 1.01 ) ) == type ( 1 ) | `` 2+2=5 '' Python edition |
Python | Let 's start by considering python3.8.5 's grammar , in this case I 'm interested to figure out how to transpile python Comparisons to c.For the sake of simplicity , let 's assume we 're dealing with a very little python trivial subset and we just want to transpile trivial Compare expressions : If I 'm not mistaken , i... | expr = Compare ( expr left , cmpop* ops , expr* comparators ) import astimport shutilimport textwrapfrom subprocess import PIPEfrom subprocess import Popenclass Visitor ( ast.NodeVisitor ) : def visit ( self , node ) : ret = super ( ) .visit ( node ) if ret is None : raise Exception ( `` Unsupported node '' ) return re... | How to transpile python Compare ast nodes to c ? |
Python | For example : sorts the data but in alphabetical order but How to sort in the list by length and then in reverse alphabetical order ? | a= [ ' a ' , ' b ' , 'zzz ' , 'ccc ' , 'ddd ' ] # before sortinga= [ ' b ' , ' a ' , 'zzz ' , 'ddd ' , 'ccc ' ] # after sortinga.sort ( key=len ) | How to sort a list by length and then in reverse alphabetical order |
Python | The following code throws up a mysterious error that I can not find the solution to . It works fine when I tested it in a bigger module , so can not see why this does n't work : CodeError MessageIt is worth noting that the code works fine when there are no additions to the file contents . On adding a student to the fil... | import csvwith open ( 'studentinfo.txt ' , ' a ' ) as fo : # open the file in append mode ( add to file , we do n't wish to overwrite ! ) studentfileWriter=csv.writer ( fo ) # fo = file out ( this can be called anything you like ) id=input ( `` Enter Student Id : '' ) firstname=input ( `` Enter firstname : '' ) surname... | Can anyone explain the root of this index out of range error ? |
Python | I know how to specify which hooks are run when . What I want to know is if it is possible to pass config into the hook via the hgrc file . Extensions can do this , e.g.I want to be able to do something similar for hooks , e.g.Is something like this possible ? Searching for a way to do this has n't turned up anything us... | [ extensions ] someextension = something [ someextension ] some.config = 1some.other.config = True [ hooks ] changegroup.mail_someone = python : something [ changegroup.mail_someone ] to_address = some.email.address @ somewhere.com | Can I configure mercurial hooks like some extensions are configured in the hgrc file ? |
Python | In python , you can learn memory location of variables by using id function , so : I 'm tried to access to variable with pointers in C ( Surely the other program still alive ) : I compile the code , no errors or warnings but when i tried the running program OS giving a Segmentation error . How i can solve this problem ... | X = `` Hello world ! `` print ( id ( X ) ) # Output is equal to 139806692112112 ( 0x7F27483876F0 ) # include < stdio.h > int main ( void ) { char *x = ( char * ) 0x7F27483876F0 ; printf ( `` % s\n '' , x ) ; return 0 ; } | Accessing a variable of the another program in C |
Python | I am writing a Fractions class and while messing around I noticed this : Why is this ? | > > > class Test : def __init__ ( self ) : pass > > > Test ( ) > Test ( ) True > > > Test ( ) > Test ( ) False | Two python objects both greater than or less than each other |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.