title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Assigning same session ID for returning users with Python Flask app
39,925,702
<p>I have a simple Flask webapp that does not require users to log in. However, I would like to assign an identifier to a user so that same users can be identified without user's log-in id. Is there a way to achieve this? </p>
-1
2016-10-07T20:58:00Z
39,926,465
<p>You can put information in the session and recover it in server-side using flask session:</p> <pre><code>from flask import Flask, session, redirect, url_for, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': session['cookie-parameter'] = request.form['data-from-form'] return redirect(url_for('other_endpoint')) return redirect(url_for('other_endpoint')) @app.route('/other-url') def other_endpoint(): session.pop('cookie-parameter', None) return redirect(url_for('index')) # Don't forget to add the secret key app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' </code></pre> <p>Hope it helps!</p>
1
2016-10-07T22:08:27Z
[ "python", "flask" ]
Error Installing PySCIPOpt on Mac OSX
39,925,751
<p>After installing SCIP Optimization Suite on OS X by compiling the source and installing Cython, </p> <pre><code>make make install INSTALLDIR="/usr/local/" make SHARED=true GMP=false READLINE=false scipoptlib pip install Cython </code></pre> <p>the installation of <code>PySCIPOpt</code> was attempted</p> <pre><code>git clone https://github.com/SCIP-Interfaces/PySCIPOpt.git cd PySCIPOpt $ SCIPOPTDIR=./ python setup.py install </code></pre> <p>But this gave an error. Any suggestions?</p> <pre><code>Traceback (most recent call last): File "setup.py", line 29, in &lt;module&gt; scipsrcdir = sorted(scipsrcdir)[-1] # use the latest version IndexError: list index out of range </code></pre> <hr> <h2>Problem importing library</h2> <p>After successfully installing <code>pyscipopt</code>, when the library is being imported using</p> <pre><code>from pyscipopt.scip import Model </code></pre> <p>I get the <code>Library not loaded</code> error</p> <pre><code> File "test.py", line 1, in &lt;module&gt; from pyscipopt import Model File "/Users/test/anaconda/envs/test/lib/python2.7/site-packages/pyscipopt/__init__.py", line 3, in &lt;module&gt; from pyscipopt.scip import Model ImportError: dlopen(/Users/test/anaconda/envs/test/lib/python2.7/site-packages/pyscipopt/scip.so, 2): Library not loaded: lib/libscipopt-3.2.1.darwin.x86_64.gnu.opt.so Referenced from: /Users/test/anaconda/envs/test/lib/python2.7/site-packages/pyscipopt/scip.so Reason: image not found </code></pre> <p>After some searching, I tried someone's solution:</p> <pre><code>export DYLD_LIBRARY_PATH=/path/to/scipoptsuite-3.2.1/lib </code></pre> <p>but running the Python file again gives a different error <code>Symbol not found: _history_length</code></p> <pre><code>Traceback (most recent call last): File "test.py", line 1, in &lt;module&gt; from pyscipopt import Model File "/Users/test/anaconda/envs/test/lib/python2.7/site-packages/pyscipopt/__init__.py", line 3, in &lt;module&gt; from pyscipopt.scip import Model ImportError: dlopen(/Users/test/anaconda/envs/test/lib/python2.7/site-packages/pyscipopt/scip.so, 2): Symbol not found: _history_length Referenced from: /Users/test/Desktop/scipoptsuite-3.2.1/lib/libscipopt-3.2.1.darwin.x86_64.gnu.opt.so Expected in: flat namespace in /Users/test/Desktop/scipoptsuite-3.2.1/lib/libscipopt-3.2.1.darwin.x86_64.gnu.opt.so </code></pre>
0
2016-10-07T21:01:21Z
39,925,979
<p>When you set the SCIPOPTDIR environment variable, it looks for directories of the form ${SCIPOPTDIR}/scip-*/src.</p> <p>You get that error because you do not have any directories that match that form in a freshly cloned checkout of PySCIPopt.git. You need to set that environment variable to the directory where you installed the "SCIP Optimization Suite".</p>
0
2016-10-07T21:21:20Z
[ "python", "osx", "python-2.7", "scip", "pyscipopt" ]
Error Installing PySCIPOpt on Mac OSX
39,925,751
<p>After installing SCIP Optimization Suite on OS X by compiling the source and installing Cython, </p> <pre><code>make make install INSTALLDIR="/usr/local/" make SHARED=true GMP=false READLINE=false scipoptlib pip install Cython </code></pre> <p>the installation of <code>PySCIPOpt</code> was attempted</p> <pre><code>git clone https://github.com/SCIP-Interfaces/PySCIPOpt.git cd PySCIPOpt $ SCIPOPTDIR=./ python setup.py install </code></pre> <p>But this gave an error. Any suggestions?</p> <pre><code>Traceback (most recent call last): File "setup.py", line 29, in &lt;module&gt; scipsrcdir = sorted(scipsrcdir)[-1] # use the latest version IndexError: list index out of range </code></pre> <hr> <h2>Problem importing library</h2> <p>After successfully installing <code>pyscipopt</code>, when the library is being imported using</p> <pre><code>from pyscipopt.scip import Model </code></pre> <p>I get the <code>Library not loaded</code> error</p> <pre><code> File "test.py", line 1, in &lt;module&gt; from pyscipopt import Model File "/Users/test/anaconda/envs/test/lib/python2.7/site-packages/pyscipopt/__init__.py", line 3, in &lt;module&gt; from pyscipopt.scip import Model ImportError: dlopen(/Users/test/anaconda/envs/test/lib/python2.7/site-packages/pyscipopt/scip.so, 2): Library not loaded: lib/libscipopt-3.2.1.darwin.x86_64.gnu.opt.so Referenced from: /Users/test/anaconda/envs/test/lib/python2.7/site-packages/pyscipopt/scip.so Reason: image not found </code></pre> <p>After some searching, I tried someone's solution:</p> <pre><code>export DYLD_LIBRARY_PATH=/path/to/scipoptsuite-3.2.1/lib </code></pre> <p>but running the Python file again gives a different error <code>Symbol not found: _history_length</code></p> <pre><code>Traceback (most recent call last): File "test.py", line 1, in &lt;module&gt; from pyscipopt import Model File "/Users/test/anaconda/envs/test/lib/python2.7/site-packages/pyscipopt/__init__.py", line 3, in &lt;module&gt; from pyscipopt.scip import Model ImportError: dlopen(/Users/test/anaconda/envs/test/lib/python2.7/site-packages/pyscipopt/scip.so, 2): Symbol not found: _history_length Referenced from: /Users/test/Desktop/scipoptsuite-3.2.1/lib/libscipopt-3.2.1.darwin.x86_64.gnu.opt.so Expected in: flat namespace in /Users/test/Desktop/scipoptsuite-3.2.1/lib/libscipopt-3.2.1.darwin.x86_64.gnu.opt.so </code></pre>
0
2016-10-07T21:01:21Z
39,925,987
<p>You need to have SCIP installed first. The shared library of the SCIP Optimization Suite to be precise. The environment variable SCIPOPTDIR must then be set to its root directory - not the directory of the Python interface. Please follow the instructions in the INSTALL file carefully: <a href="https://github.com/SCIP-Interfaces/PySCIPOpt/blob/master/INSTALL.md" rel="nofollow">https://github.com/SCIP-Interfaces/PySCIPOpt/blob/master/INSTALL.md</a></p>
0
2016-10-07T21:21:57Z
[ "python", "osx", "python-2.7", "scip", "pyscipopt" ]
Flask-peewee to Flask-sqlalchmey - Operand should contain 1 column(s)
39,925,767
<p>I am having an issue with this error Operand should contain 1 column(s), I get that is about their being two fields in the subquery but from my code and using flask-sqlalchemy I can't work out what is going wrong. I am converting my application from flask-peewee to flask-sqlalchemy and it is this one issue that I can't work out.</p> <p>Here it the main query code the first one is my new sql-alchemy query and the other is the peewee one. </p> <pre><code>//SqlAlchmey return UserBeer.query.filter(or_( UserBeer.id &lt; self.following(), UserBeer.username == self)).order_by(UserBeer.tried_date.desc()).limit(5) //Peewee Query return UserBeer.select(Beer, UserBeer).join(Beer).where( (UserBeer.username &lt;&lt; self.following()) | (UserBeer.username == self)).order_by(UserBeer.tried_date.desc()).limit(5) </code></pre> <p>The part of the query that is causing the issue is the call to <code>self.following()</code> if I remove that the sqlalchemy query works here is the code for that query bellow is the contents of <code>self.following()</code></p> <pre><code>// SQLAlchmey return Relationship.query.filter(Relationship.from_user == self) //Peewee return ( User.select().join(Relationship, on=Relationship.to_user).where(Relationship.from_user == self)) </code></pre> <p>I know the second query I am asking for two different things but it seems like you declare the relationships in the models in SQLAlchemy here is the relationship model I think it is right but not sure. Also my user model not sure if there is something missing.</p> <pre><code>class Relationship(db.Model): id = db.Column(db.Integer, primary_key=True) from_user_id = db.Column(db.Integer, db.ForeignKey('user.id')) to_user_id = db.Column(db.Integer, db.ForeignKey('user.id')) from_user = db.relationship('User', backref=db.backref('relationships', lazy='joined'), foreign_keys=from_user_id) to_user = db.relationship('User', backref=db.backref('related_to', lazy='joined'), foreign_keys=to_user_id) class User(UserMixin, db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(), unique=True) email = db.Column(db.String(), unique=True) bio = db.Column(db.String(160)) password = db.Column(db.String(200)) joined_at = db.Column(db.DateTime(), default=datetime.datetime.now) is_admin = db.Column(db.Boolean(), default=False) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) </code></pre> <p><strong>EDIT</strong> I thought the whole error might be useful when I was looking it over again</p> <pre><code>OperationalError: (_mysql_exceptions.OperationalError) (1241, 'Operand should contain 1 column(s)') [SQL: u'SELECT user_beer.id AS user_beer_id, user_beer.username_id AS user_beer_username_id, user_beer.beer_id AS user_beer_beer_id, user_beer.rating AS user_beer_rating, user_beer.description AS user_beer_description, user_beer.recommend AS user_beer_recommend, user_beer.tried_date AS user_beer_tried_date \nFROM user_beer \nWHERE user_beer.id &lt; (SELECT relationship.id AS relationship_id, relationship.from_user_id AS relationship_from_user_id, relationship.to_user_id AS relationship_to_user_id \nFROM relationship \nWHERE %s = relationship.from_user_id) OR %s = user_beer.username_id ORDER BY user_beer.tried_date DESC \n LIMIT %s'] [parameters: (1L, 1L, 5)] </code></pre>
0
2016-10-07T21:03:28Z
39,925,998
<blockquote> <p>OperationalError: (_mysql_exceptions.OperationalError) (1241, 'Operand should contain 1 column(s)')</p> </blockquote> <p>tells you that you're trying to compare a list of columns to one user id column.</p> <pre><code>return UserBeer.query.filter(or_( UserBeer.id &lt; self.following(), UserBeer.username == self)).order_by(UserBeer.tried_date.desc()).limit(5) </code></pre> <p>in the code above <code>UserBeer.id</code> is one column value and <code>self.following()</code> is multiple column value.</p>
1
2016-10-07T21:23:28Z
[ "python", "mysql", "flask-sqlalchemy", "flask-peewee" ]
Flask-peewee to Flask-sqlalchmey - Operand should contain 1 column(s)
39,925,767
<p>I am having an issue with this error Operand should contain 1 column(s), I get that is about their being two fields in the subquery but from my code and using flask-sqlalchemy I can't work out what is going wrong. I am converting my application from flask-peewee to flask-sqlalchemy and it is this one issue that I can't work out.</p> <p>Here it the main query code the first one is my new sql-alchemy query and the other is the peewee one. </p> <pre><code>//SqlAlchmey return UserBeer.query.filter(or_( UserBeer.id &lt; self.following(), UserBeer.username == self)).order_by(UserBeer.tried_date.desc()).limit(5) //Peewee Query return UserBeer.select(Beer, UserBeer).join(Beer).where( (UserBeer.username &lt;&lt; self.following()) | (UserBeer.username == self)).order_by(UserBeer.tried_date.desc()).limit(5) </code></pre> <p>The part of the query that is causing the issue is the call to <code>self.following()</code> if I remove that the sqlalchemy query works here is the code for that query bellow is the contents of <code>self.following()</code></p> <pre><code>// SQLAlchmey return Relationship.query.filter(Relationship.from_user == self) //Peewee return ( User.select().join(Relationship, on=Relationship.to_user).where(Relationship.from_user == self)) </code></pre> <p>I know the second query I am asking for two different things but it seems like you declare the relationships in the models in SQLAlchemy here is the relationship model I think it is right but not sure. Also my user model not sure if there is something missing.</p> <pre><code>class Relationship(db.Model): id = db.Column(db.Integer, primary_key=True) from_user_id = db.Column(db.Integer, db.ForeignKey('user.id')) to_user_id = db.Column(db.Integer, db.ForeignKey('user.id')) from_user = db.relationship('User', backref=db.backref('relationships', lazy='joined'), foreign_keys=from_user_id) to_user = db.relationship('User', backref=db.backref('related_to', lazy='joined'), foreign_keys=to_user_id) class User(UserMixin, db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(), unique=True) email = db.Column(db.String(), unique=True) bio = db.Column(db.String(160)) password = db.Column(db.String(200)) joined_at = db.Column(db.DateTime(), default=datetime.datetime.now) is_admin = db.Column(db.Boolean(), default=False) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) </code></pre> <p><strong>EDIT</strong> I thought the whole error might be useful when I was looking it over again</p> <pre><code>OperationalError: (_mysql_exceptions.OperationalError) (1241, 'Operand should contain 1 column(s)') [SQL: u'SELECT user_beer.id AS user_beer_id, user_beer.username_id AS user_beer_username_id, user_beer.beer_id AS user_beer_beer_id, user_beer.rating AS user_beer_rating, user_beer.description AS user_beer_description, user_beer.recommend AS user_beer_recommend, user_beer.tried_date AS user_beer_tried_date \nFROM user_beer \nWHERE user_beer.id &lt; (SELECT relationship.id AS relationship_id, relationship.from_user_id AS relationship_from_user_id, relationship.to_user_id AS relationship_to_user_id \nFROM relationship \nWHERE %s = relationship.from_user_id) OR %s = user_beer.username_id ORDER BY user_beer.tried_date DESC \n LIMIT %s'] [parameters: (1L, 1L, 5)] </code></pre>
0
2016-10-07T21:03:28Z
39,965,552
<p>Switching from Peewee to SQLAlchemy? Why on earth would you do such a thing!</p> <p>Honestly, if you've run into what you believe is a bug in Peewee, or find things overly difficult or un-intuitive, that is exactly the most useful kind of feedback for me as the maintainer. Sure, it's nice hearing from people who say "Peewee is great, thanks", but it's the folks who end up leaving that generally have the most to say.</p> <p>Please stop by and leave a comment <a href="https://github.com/coleifer/peewee/issues/new" rel="nofollow">https://github.com/coleifer/peewee/issues/new</a> or hit me up at <a href="http://charlesleifer.com/contact/" rel="nofollow">http://charlesleifer.com/contact/</a> -- I'd be extremely grateful for even a few minutes of your time.</p>
0
2016-10-10T19:39:10Z
[ "python", "mysql", "flask-sqlalchemy", "flask-peewee" ]
False iteration over list
39,925,817
<p>I have a function that's suppose to minimize the quantity of a letter in a list if a given word contains that letter. That's the def of the function:</p> <pre><code>word = 'better' hand = {'b':1, 'r':1, 's':3, 't':2, 'z':1, 'e':3} def updateHand(hand, word): handCopy = hand.copy() for x in word: print(x) print(hand) handCopy[x] = hand.get(x,0) - 1 print(handCopy) return handCopy </code></pre> <p>And that's the Output:</p> <pre><code>b {'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3} {'s': 3, 'b': 0, 'z': 1, 't': 2, 'r': 1, 'e': 3} e {'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3} {'s': 3, 'b': 0, 'z': 1, 't': 2, 'r': 1, 'e': 2} t {'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3} {'s': 3, 'b': 0, 'z': 1, 't': 1, 'r': 1, 'e': 2} t {'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3} {'s': 3, 'b': 0, 'z': 1, 't': 1, 'r': 1, 'e': 2} e {'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3} {'s': 3, 'b': 0, 'z': 1, 't': 1, 'r': 1, 'e': 2} r {'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3} {'s': 3, 'b': 0, 'z': 1, 't': 1, 'r': 0, 'e': 2} Out[110]: {'b': 0, 'e': 2, 'r': 0, 's': 3, 't': 1, 'z': 1} </code></pre> <p>Why is my function skipping the second <code>t</code> and / or doesn't eliminate it from the list? Thanks!</p>
0
2016-10-07T21:07:45Z
39,926,144
<p>Let's consider this situation:</p> <pre><code>hand = {'b':1, 'r':1, 's':3, 't':2, 'z':1, 'e':3} </code></pre> <p>so we have hand as a dict. Now we do this one:</p> <pre><code>x = hand.get('t',0) - 1 print x </code></pre> <p>result will be 1. Let's do it again:</p> <pre><code>x = hand.get('t',0) - 1 print x </code></pre> <p>again 1. Why? Because you're not updating value for <code>'t'</code> key in hand dict. So it's the same situation as in your code:</p> <pre><code>handCopy[x] = hand.get(x,0) - 1 </code></pre> <p>so you should do it in this way:</p> <pre><code>handCopy[x] = handCopy.get(x, 0) - 1 </code></pre> <p><strong>Solution</strong></p> <pre><code>word = 'better' hand = {'b':1, 'r':1, 's':3, 't':2, 'z':1, 'e':3} def updateHand(hand, word): handCopy = hand.copy() for x in word: print(x) print(hand) handCopy[x] = handCopy.get(x,0) - 1 print(handCopy) return handCopy </code></pre> <p>result:</p> <pre><code>b {'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1} {'s': 3, 'b': 0, 'e': 3, 't': 2, 'r': 1, 'z': 1} e {'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1} {'s': 3, 'b': 0, 'e': 2, 't': 2, 'r': 1, 'z': 1} t {'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1} {'s': 3, 'b': 0, 'e': 2, 't': 1, 'r': 1, 'z': 1} t {'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1} {'s': 3, 'b': 0, 'e': 2, 't': 0, 'r': 1, 'z': 1} e {'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1} {'s': 3, 'b': 0, 'e': 1, 't': 0, 'r': 1, 'z': 1} r {'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1} {'s': 3, 'b': 0, 'e': 1, 't': 0, 'r': 0, 'z': 1} Out[110]: {'s': 3, 'b': 0, 'e': 1, 't': 0, 'r': 0, 'z': 1} </code></pre>
0
2016-10-07T21:36:22Z
[ "python", "list", "dictionary", "iteration" ]
Kivy - hard to select Widgets
39,925,847
<p>I have written a simple application and deployed it on Sony Xperia Z and Galaxy Prime devices. On both it's really very hard (I've got to click many times before it reacts) to:</p> <ul> <li>put focus on a TextInput</li> <li>select a ToggleButton</li> <li>click a Button</li> <li>etc.</li> </ul> <p>The same time a ScrollView (that is the container for the mentioned widgets) works perfectly smooth. And when run on desktop then it's alright.</p> <p>I use kivy 1.9.1, python 2.7, build on Ubuntu 16 using buildozer. Don't know what else could I say... (Let me know, please) Have you experienced such an issue? </p>
0
2016-10-07T21:09:51Z
39,929,515
<p>You should update to kivy 1.9.2-dev, the problem is fixed there. In <code>buildozer.spec</code> file, write requirement <code>kivy==master</code>.</p>
3
2016-10-08T06:41:41Z
[ "android", "python", "kivy" ]
How to use distancematrix function from Biopython?
39,925,865
<p>I would like to calculate the distance matrix (using genetic distance function) on a data set using <a href="http://biopython.org/DIST/docs/api/Bio.Cluster.Record-class.html#distancematrix" rel="nofollow">http://biopython.org/DIST/docs/api/Bio.Cluster.Record-class.html#distancematrix</a>, but I seem to keep getting errors, typically telling me the rank is not of 2. I'm not actually sure what it wants as an input since the documentation never says and there are no examples online.</p> <p>Say I read in some aligned gene sequences:</p> <pre><code>SingleLetterAlphabet() alignment with 7 rows and 52 columns AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRL...SKA COATB_BPIKE/30-81 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKL...SRA Q9T0Q8_BPIKE/1-52 DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRL...SKA COATB_BPI22/32-83 AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73 </code></pre> <p>which would be done by </p> <pre><code>data = Align.read("dataset.fasta","fasta") </code></pre> <p>But the distance matrix in Cluster.Record class does not accept this. How can I get it to work! ie</p> <pre><code>dist_mtx = distancematrix(data) </code></pre>
1
2016-10-07T21:11:15Z
39,932,031
<p>The short answer: You don't.</p> <p>From the <a href="http://biopython.org/DIST/docs/api/Bio.Cluster.Record-class.html" rel="nofollow">documentation</a>:</p> <blockquote> <p>A Record stores the gene expression data and related information</p> </blockquote> <p>The <code>Cluster</code> object is used for gene expression data and not for MSA. I would recommend using an external tool like <a href="https://almob.biomedcentral.com/articles/10.1186/1748-7188-9-12" rel="nofollow">MSARC</a> which runs in Python as well.</p>
0
2016-10-08T11:55:04Z
[ "python", "biopython" ]
Pandas bar graph using original dataframe
39,925,873
<p>I have a pandas dataframe and I'm attempting to plot the number of subscription types purchased by gender the original dataframe resemblems</p> <pre><code>df = Memb_ID Gender 1_Month 3_Month 6_Month 1_Year 1 Male 6 0 3 0 2 Male 0 0 0 4 3 Female 0 4 3 1 4 Male 2 1 0 1 5 Female 1 4 0 2 ... </code></pre> <p>At the moment I make a <code>temp_df</code> where I sum up the data so that I have</p> <pre><code>temp_df = pd.DataFrame(columns=['Gender', '1_Year', '1_Month', '3_Month','6_Month']) sex = ['Male', 'Female'] temp_df['Gender'] = sex for i in list(temp_df.columns.values)[1:]: temp = [df.loc[df['Gender'] == 'Male', i].sum(),\ df.loc[df['Gender'] == 'Female', i].sum()] temp_df[i] = temp temp_df.plot(x='Gender', kind='bar', grid=True) plt.show() </code></pre> <p>This fills up <code>temp_df</code> and I'm able to graph it. Is there an eloquent way of performing the same thing using just <code>df</code>?</p>
1
2016-10-07T21:12:04Z
39,926,013
<p>You can use <code>groupby().sum()</code> to replace the <code>temp_df</code>:</p> <pre><code>ax = df.groupby('Gender')['1_Year','1_Month','3_Month','6_Month'].sum().plot.bar(grid=True) </code></pre> <p><a href="http://i.stack.imgur.com/2hzw9.png" rel="nofollow"><img src="http://i.stack.imgur.com/2hzw9.png" alt="enter image description here"></a></p>
4
2016-10-07T21:24:36Z
[ "python", "pandas", "plot" ]
How to avoid to manually set the initial value of a variable in a recursive function?
39,925,931
<p>I found this solution for the Euler project 5 (What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?) with a variable range of integer values to divide evenly by: </p> <pre><code>def Euler5(start, end, counter): x = counter while start &lt;= end: if x%counter == x%start: return Euler5(start+1, end, x) else: x += counter return x </code></pre> <p>I do however have to manually set the counter to the smallest integer value (initial <code>counter</code> = <code>start</code> value). Is there a way to automatically do this and to maintain the algorithm?</p>
4
2016-10-07T21:17:08Z
39,926,039
<p>If I understood you right, you want that <code>counter == start</code> for the initial call without specifying the <code>counter</code> manually in the first call.</p> <p>For this, you can set <code>counter</code> to a default value of <code>None</code> and check for this at the beginning of the function, setting <code>counter</code> to the appropriate value if this is the case:</p> <pre><code>def Euler5(start, end, counter=None): if counter is None: counter = start x = counter while start &lt;= end: if x % counter == x % start: return Euler5(start+1, end, x) else: x += counter return x </code></pre>
3
2016-10-07T21:26:43Z
[ "python" ]
Login system with infinite loop error
39,925,960
<p>I'm coding myself a "simple" login system everything works ok up until the <code>LOGIN</code> part.</p> <p>The <code>while</code> loop at the end only happens once even though I put another user rather than what I created when I ran the program. I got it to work at some point, but then there was another issue where the <code>while</code> loop would happen over and over again.</p> <pre><code>import re users = {} status = "" while status != "r": status = input("Press R to register!\n") if status == "r": createUser = input("Create your Username: ") while len(createUser)&lt; 5: #checks user len print("Username should contain at least 5 characters!") createUser = input("Create your Username: ") #repeat if user len &lt; 5 while not re.match("^[a-z]*$" , createUser): # denies blank spaces print("Cannot use blank spaces") createUser = input("Create your Username: ") if createUser in users: print("Username already used!") else: createPass = input("Create your Password: ") while len(createPass) &lt; 5: #checks pass len print("Password too short!\n Password should contain at least 5 characters!\n") createPass = input("Create your Password: ") #repeat if pass len &lt; 5 while not re.match("^[a-z]*$", createPass): # denies blank spaces print("Cannot use blank spaces") createPass = input("Create your Password: ") else: users[createUser] = createPass #adds user and pass to users print("User created!") #LOGIN for createUser in users: username = input("Username: ") if username == createUser in users: password = input("Password: ") else: while username != createUser: print("User unregistered! Please register!") createUser = input("Create your Username:") </code></pre>
0
2016-10-07T21:19:55Z
39,967,978
<p>Try this:</p> <pre><code>def login(): username = input("Username: ") if username not in users: print("User unregistered! Please register!") register() return password = input("Password: ") if users[username] != password print("Password invalid") </code></pre> <p>I've rewritten your code here. Notice how I've broken it down into functions which do one thing:</p> <ul> <li>usernameValidator</li> <li>passwordValidator</li> <li>getUsername</li> <li>getPassword</li> <li>register</li> <li>login</li> </ul> <p>Beginning of the program:</p> <pre><code>import re users = {} </code></pre> <p>Now we define some validators to check if the username/password are correct:</p> <pre><code>def usernameValidator(username): errorMessage = "" if len(username) &lt; 5: errorMessage += "Username should contain at least 5 characters!\n" if not re.match("^[a-z]*$" , username): # Note... this checks for more than just blank spaces! errorMessage += "Cannot use blank spaces\n" if username in users: errorMessage += "Username already used!\n" return errorMessage def passwordValidator(password): errorMessage = "" if len(password) &lt; 5: errorMessage += "Password should contain at least 5 characters!\n" if not re.match("^[a-z]*$" , password): # Note... this checks for more than just blank spaces! errorMessage += "Cannot use blank spaces\n" return errorMessage </code></pre> <p>Now we write the getUsername/getPassword functions which talk with the user:</p> <pre><code>def getUsername(): username = input("Create your Username: ") errorMsg = usernameValidator(username) print(errorMsg) return username if errorMsg == "" else "" def getPassword(): password = input("Create your Password: ") errorMsg = passwordValidator(password) print(errorMsg) return password if errorMsg == "" else "" </code></pre> <p>Putting it all together, we write register/login:</p> <pre><code>def register(): username = "" password = "" while username == "": username = getUsername() while password == "": password = getPassword() users[username] = password print("User created!") def login(): username = input("Username: ") if username not in users: print("User unregistered! Please register!") register() return password = input("Password: ") if users[username] != password: print("Password invalid") </code></pre> <p>Finally, we may run:</p> <pre><code>while True: status = input("Press R to register!\nPress L to login\n") if status.lower() == "r": register() if status.lower() == "l": login() </code></pre> <p><a href="https://repl.it/DsrJ" rel="nofollow">Try it online</a>.</p>
1
2016-10-10T22:56:42Z
[ "python" ]
Login system with infinite loop error
39,925,960
<p>I'm coding myself a "simple" login system everything works ok up until the <code>LOGIN</code> part.</p> <p>The <code>while</code> loop at the end only happens once even though I put another user rather than what I created when I ran the program. I got it to work at some point, but then there was another issue where the <code>while</code> loop would happen over and over again.</p> <pre><code>import re users = {} status = "" while status != "r": status = input("Press R to register!\n") if status == "r": createUser = input("Create your Username: ") while len(createUser)&lt; 5: #checks user len print("Username should contain at least 5 characters!") createUser = input("Create your Username: ") #repeat if user len &lt; 5 while not re.match("^[a-z]*$" , createUser): # denies blank spaces print("Cannot use blank spaces") createUser = input("Create your Username: ") if createUser in users: print("Username already used!") else: createPass = input("Create your Password: ") while len(createPass) &lt; 5: #checks pass len print("Password too short!\n Password should contain at least 5 characters!\n") createPass = input("Create your Password: ") #repeat if pass len &lt; 5 while not re.match("^[a-z]*$", createPass): # denies blank spaces print("Cannot use blank spaces") createPass = input("Create your Password: ") else: users[createUser] = createPass #adds user and pass to users print("User created!") #LOGIN for createUser in users: username = input("Username: ") if username == createUser in users: password = input("Password: ") else: while username != createUser: print("User unregistered! Please register!") createUser = input("Create your Username:") </code></pre>
0
2016-10-07T21:19:55Z
39,967,987
<p>First, <code>"^[a-z]*$"</code> tests for no lowercase letters, it does not mean "no blank spaces", so I have corrected that for you with <code>"\\s+"</code></p> <p>You really need to learn about methods and break your problem down. </p> <p>1) Ask for the username</p> <pre><code>def get_username(): while True: uname = input("Create your Username: ") if len(uname) &lt; 5: print("Username should contain at least 5 characters!") continue if re.search("\\s+", uname): print("Cannot use blank spaces") continue break # input successful return uname </code></pre> <p>2) Ask for the password</p> <pre><code>def get_password(): while True: passwd = input("Create your Password: ") if len(passwd) &lt; 5: print("Password too short!\n\tPassword should contain at least 5 characters!\n") continue if re.search("\\s+", passwd): print("Cannot use blank spaces") continue break # input successful return passwd </code></pre> <p>3) Register</p> <pre><code>def register(): while True: uname = get_username() if uname not in users: break # continue to get password else: print("Username already used!") passwd = get_password() if passwd: users[uname] = passwd print("User created!") </code></pre> <p>4) Attempt login (3 max attempts). It is currently unclear how you want to run this... </p> <pre><code>def login(): for i in range(3): username = input("Username: ") if username in users: password = input("Password: ") if users[username] != password: print("Wrong username or password") else: print("User does not exist") else: print("Max attempts reached") </code></pre> <p>5) (optional) Learn about <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow">D.R.Y</a> since your tests are essentially the same</p> <pre><code>def test_input(s): if len(s) &lt; 5: print("Input should contain at least 5 characters!") return False if re.search("\\s+", s): print("Cannot use blank spaces") return False return True </code></pre> <p>6) Run some code that uses all these methods. </p> <pre><code>status = input("Press R to register!\n") if status.lower() == "r": register() </code></pre>
1
2016-10-10T22:57:33Z
[ "python" ]
function using dictionary as argument
39,925,976
<p>I have created a dictionary with values for Velocity, temperature and altitude:</p> <pre><code>mach_dict = dict(velocity=[], altitude=[], temperature=[]) </code></pre> <p>Which I use to store values for a flying plain at climb, cruise and descent segments.</p> <pre><code>mach_dict = {'velocity': [0, 300, 495, 500, 300], 'altitude': [288.15, 288.15, 288.15, 288.15, 288.15], 'temperature': [0, 0, 50, 50, 50]} </code></pre> <p>I need to create a function (def) that returns a dictionary that stores the mach number for every segment. </p> <p>To estimate <code>Mach</code> I use the formula:</p> <pre><code>Mach = velocity / sqrt(1.4 * 286 * (Temperature - altitude * 0.05)) </code></pre> <p>Can anybody help on that? </p>
0
2016-10-07T21:21:02Z
39,926,078
<p>You can <code>zip</code> the list values in the dictionary and compute the new key <code>mach_number</code> using a <em>list comprehension</em>:</p> <pre><code>import math def compute_mach(velocity, altitude, temperature): return velocity/math.sqrt(1.4*286*(temperature-altitude*0.05)) mach_dict['mach_number'] = [compute_mach(v, a, t) for v, a, t in zip(mach_dict['velocity'], mach_dict['altitude'], mach_dict['temperature'])] </code></pre>
0
2016-10-07T21:30:16Z
[ "python", "function", "dictionary", "arguments" ]
function using dictionary as argument
39,925,976
<p>I have created a dictionary with values for Velocity, temperature and altitude:</p> <pre><code>mach_dict = dict(velocity=[], altitude=[], temperature=[]) </code></pre> <p>Which I use to store values for a flying plain at climb, cruise and descent segments.</p> <pre><code>mach_dict = {'velocity': [0, 300, 495, 500, 300], 'altitude': [288.15, 288.15, 288.15, 288.15, 288.15], 'temperature': [0, 0, 50, 50, 50]} </code></pre> <p>I need to create a function (def) that returns a dictionary that stores the mach number for every segment. </p> <p>To estimate <code>Mach</code> I use the formula:</p> <pre><code>Mach = velocity / sqrt(1.4 * 286 * (Temperature - altitude * 0.05)) </code></pre> <p>Can anybody help on that? </p>
0
2016-10-07T21:21:02Z
39,926,088
<p>You'd zip together the 3 lists to produce <code>velocity, altitude, temperature</code> tuples:</p> <pre><code>mach_dict['mach'] = mach_per_section = [] for vel, alt, temp in zip( mach_dict['velocity'], mach_dict['altitude'], mach_dict['temperature']): mach = vel / sqrt(1.4 * 286 * (temp - alt * 0.05)) mach_per_section.append(mach) </code></pre> <p>Unfortunately, your inputs lead to a <code>ValueError: math domain error</code> because for some you'd get a negative value for <code>1.4 * 286 * (temp - alt * 0.05)</code>.</p>
0
2016-10-07T21:31:02Z
[ "python", "function", "dictionary", "arguments" ]
function using dictionary as argument
39,925,976
<p>I have created a dictionary with values for Velocity, temperature and altitude:</p> <pre><code>mach_dict = dict(velocity=[], altitude=[], temperature=[]) </code></pre> <p>Which I use to store values for a flying plain at climb, cruise and descent segments.</p> <pre><code>mach_dict = {'velocity': [0, 300, 495, 500, 300], 'altitude': [288.15, 288.15, 288.15, 288.15, 288.15], 'temperature': [0, 0, 50, 50, 50]} </code></pre> <p>I need to create a function (def) that returns a dictionary that stores the mach number for every segment. </p> <p>To estimate <code>Mach</code> I use the formula:</p> <pre><code>Mach = velocity / sqrt(1.4 * 286 * (Temperature - altitude * 0.05)) </code></pre> <p>Can anybody help on that? </p>
0
2016-10-07T21:21:02Z
39,926,108
<p>Technically, this is modifying the passed in dictionary, and the <code>return</code> is unnecessary. </p> <pre><code>from math import sqrt def func(d): machs = [] for v, a, t in zip(d['velocity', d['altitude'], d['temperature']): mach = v / sqrt(1.4 * 286 * (t - a * 0.05)) machs.append(mach) d['mach'] = machs return d </code></pre>
0
2016-10-07T21:32:25Z
[ "python", "function", "dictionary", "arguments" ]
function using dictionary as argument
39,925,976
<p>I have created a dictionary with values for Velocity, temperature and altitude:</p> <pre><code>mach_dict = dict(velocity=[], altitude=[], temperature=[]) </code></pre> <p>Which I use to store values for a flying plain at climb, cruise and descent segments.</p> <pre><code>mach_dict = {'velocity': [0, 300, 495, 500, 300], 'altitude': [288.15, 288.15, 288.15, 288.15, 288.15], 'temperature': [0, 0, 50, 50, 50]} </code></pre> <p>I need to create a function (def) that returns a dictionary that stores the mach number for every segment. </p> <p>To estimate <code>Mach</code> I use the formula:</p> <pre><code>Mach = velocity / sqrt(1.4 * 286 * (Temperature - altitude * 0.05)) </code></pre> <p>Can anybody help on that? </p>
0
2016-10-07T21:21:02Z
39,926,129
<p>And you can use pandas and numpy to do that as well</p> <pre><code>import pandas as pd import numpy as np def compute(mach_dict): df = pd.DataFrame.from_dict(mach_dict) r = df.velocity / np.sqrt(1.4 * 286 * (df.temperature - df.altitude * 0.05)) return list(r) mach_dict={'velocity':[0, 300, 495, 500, 300],'altitude':[288.15, 288.15, 288.15, 288.15, 288.15],'temperature':[0, 0, 50, 50, 50]} print(compute(mach_dict)) </code></pre> <p>This will handle the -ve case that it would give you NaN</p>
0
2016-10-07T21:34:24Z
[ "python", "function", "dictionary", "arguments" ]
define variables in the txt file using python script
39,926,118
<p>i have one .txt file and i want to create python script with <code>sys.argv</code> or <code>argparse</code> or other package to define some variables in the txt file and i take some result.</p> <p>i want to update the variables in the text file based on arguments passed to the python script</p> <p>txt file maybe like this :</p> <pre><code>input number 1= %var1% input number 2= %var2% result = %vresult(var1-var2)% </code></pre> <p>must var1,var2 define by the user with some input in the python script and i take result(var1-var2 for ex)</p> <p>i can to do this easy but i dont know how to connect arguments from the python script to txt.</p> <p>how can i write a python script to update dynamic variables in the txt file ?</p> <p>i dont want with replace i thing so arguments is the better.</p>
0
2016-10-07T21:33:11Z
39,926,522
<p>There's almost certainly a better way to do this but it sounded like an interesting problem so I decided to give it a try. I defined a text file with variable names listed as such:</p> <p><strong>newfile.txt:</strong></p> <pre><code>x = 1 y = 2 z = 3 </code></pre> <p>By reading one line at a type and conforming to the "var = value" input format, you can parse the text file for the correct variable then re-write the file with the new value.</p> <pre><code>import fnmatch var2change = "z = 17" identifier = var2change.split('=')[0] # Get variable name # Read file file = open('newfile.txt', 'r') fileLines = file.read() fileLines = fileLines.splitlines() for lineNum,var in enumerate(fileLines): if fnmatch.fnmatch(str(var),''.join([identifier,'*'])): break # Found variable to change file.close() file = open("newfile.txt", "w") for ln, data in enumerate(fileLines): if ln == lineNum: lineToWrite = ''.join([var2change, '\n']) else: lineToWrite = ''.join([data, '\n']) file.write(lineToWrite) file.close() </code></pre> <p>This will re-write the file to read:</p> <p><strong>newfile.txt:</strong></p> <pre><code>x = 1 y = 2 z = 17 </code></pre>
0
2016-10-07T22:14:22Z
[ "python", "python-2.7", "parameter-passing", "argparse", "sys" ]
define variables in the txt file using python script
39,926,118
<p>i have one .txt file and i want to create python script with <code>sys.argv</code> or <code>argparse</code> or other package to define some variables in the txt file and i take some result.</p> <p>i want to update the variables in the text file based on arguments passed to the python script</p> <p>txt file maybe like this :</p> <pre><code>input number 1= %var1% input number 2= %var2% result = %vresult(var1-var2)% </code></pre> <p>must var1,var2 define by the user with some input in the python script and i take result(var1-var2 for ex)</p> <p>i can to do this easy but i dont know how to connect arguments from the python script to txt.</p> <p>how can i write a python script to update dynamic variables in the txt file ?</p> <p>i dont want with replace i thing so arguments is the better.</p>
0
2016-10-07T21:33:11Z
39,926,621
<p>This is a different way using <code>regex</code> and a dictionary, and taking input using <code>sys.argv</code>:</p> <pre><code>import sys,re v1 = sys.argv[1] v2 = sys.argv[2] with open('file.txt','r') as f: content = f.read() repl = {'var1':v1, 'var2':v2} repl_pattern = re.compile(r'(' + '|'.join(repl.keys()) + r')') final_data = repl_pattern.sub(lambda x: repl[x.group()], content) with open('file.txt','w') as new: new.write(final_data) </code></pre> <p><strong>results:</strong></p> <p>The file.txt initially had the following content:</p> <pre><code>input number 1= var1 input number 2= var2 result = vresult(var1-var2) </code></pre> <p>and after running the above code (with: <code>sys.argv[1]=2</code> and <code>sys.argv[2]</code>=3) the file changed to:</p> <pre><code>input number 1= 3 input number 2= 2 result = vresult(3-2) </code></pre> <p>If you want <code>result = 1</code> instead of <code>result = vresult(3-2)</code> then add this code:</p> <pre><code>result = str(int(v1)-int(v2)) key3 = 'vresult('+v1+'-'+v2+')' final_data = final_data.replace(key3,result) </code></pre> <p>just before the <code>with open('file.txt','w') as new:</code> ....</p>
1
2016-10-07T22:27:21Z
[ "python", "python-2.7", "parameter-passing", "argparse", "sys" ]
Access Functions via Dictionary
39,926,137
<p>I have a function like this:</p> <pre><code>def abc(a,b): return a+b </code></pre> <p>And I want to assign it to a dictionary like this:</p> <pre><code>functions = {'abc': abc(a,b)} </code></pre> <p>The trouble is, when assigning it to the dictionary, since the arguments are not yet defined, I get the error: </p> <pre><code>NameError: name 'a' is not defined </code></pre> <p>I would do the obvious thing and define the arguments ahead of time but I need to define them in a loop (and then call the function based on locating it in a list) like this:</p> <pre><code>functions_to_call = ['abc'] for f in functions_to_call: a=3 b=4 #This is supposed to locate and run the function from the dictionary if it is in the list of functions. if f in functions: functions[f] </code></pre>
2
2016-10-07T21:35:08Z
39,926,170
<blockquote> <p>I need to define them in a loop (and then call the function based on locating it in a list)</p> </blockquote> <p>Then what's the issue with simply saving the function object in the dictionary:</p> <pre><code>functions = {'abc':abc} </code></pre> <p>and <em>then</em> applying <code>a</code> and <code>b</code> to the function while looping:</p> <pre><code>functions_to_call = ['abc'] for f in functions_to_call: a, b = 3, 4 if f in functions: functions[f](a, b) </code></pre>
3
2016-10-07T21:38:31Z
[ "python", "list", "function", "python-3.x", "dictionary" ]
Access Functions via Dictionary
39,926,137
<p>I have a function like this:</p> <pre><code>def abc(a,b): return a+b </code></pre> <p>And I want to assign it to a dictionary like this:</p> <pre><code>functions = {'abc': abc(a,b)} </code></pre> <p>The trouble is, when assigning it to the dictionary, since the arguments are not yet defined, I get the error: </p> <pre><code>NameError: name 'a' is not defined </code></pre> <p>I would do the obvious thing and define the arguments ahead of time but I need to define them in a loop (and then call the function based on locating it in a list) like this:</p> <pre><code>functions_to_call = ['abc'] for f in functions_to_call: a=3 b=4 #This is supposed to locate and run the function from the dictionary if it is in the list of functions. if f in functions: functions[f] </code></pre>
2
2016-10-07T21:35:08Z
39,926,177
<p>You assign a reference to the function <strong>without</strong> any arguments, and then supply them when calling it:</p> <pre><code>functions = {'abc':abc} # Assignment: no arguments! functions_to_call = ['abc'] for f in functions_to_call: a=3 b=4 if f in functions: functions[f](a, b) # calling with arguments </code></pre>
3
2016-10-07T21:38:52Z
[ "python", "list", "function", "python-3.x", "dictionary" ]
Python 3: Getting two user inputs from a single line in a text file
39,926,210
<p>I am working on a program that asks the user to enter a username and password and the program checks if the username and password is in the text file. If the username and password is not in the text file, it asks if the user wants to create a new user. If the username and password matches one in the text file, it rejects the user input. If it is successful, the username and password is saved to the text file, on a new line (the username and password separated by a comma).</p> <p>text.txt :</p> <pre><code> John, Password Mary, 12345 Bob, myPassword </code></pre> <p>Usercheck.py :</p> <pre><code>input: John # Checks if 'John' in text.txt input2: Password # Checks if 'Password' in text.txt output: Hello John! # If both 'John' and 'Password' in text.txt input: Amy # Checks if 'Amy' in text.txt input2: passWoRD # Checks if 'passWoRD' in text.txt output: User does not exist! # If 'Amy' and 'passWoRD' not in text.txt output2: Would you like to create a new user? # If 'yes' output3: What will be your username? input3: Amy # Checks if 'Amy' in text.txt output4: What will be your password? input4: passWoRD # Adds 'Amy, passWoRD' to a new line in text.txt </code></pre> <p>How could I check the text file text.txt for a username AND password that is separated by a ',' without the user entering a ','? And also be able to create a new username and password (which is separated by a ','), adding it to the text file?</p>
1
2016-10-07T21:42:56Z
39,926,342
<p>You may know the <code>open()</code> function. With this function you can open a file like this: </p> <pre><code>open('text.txt', 'a') </code></pre> <p>Parameter 1 is the file and parameter 2 is the mode (r for read only, w for write only and a for both and appending)</p> <p>So to read the open file line by line :</p> <pre><code>file = open('text.txt', 'a') lines = file.readlines() for line in lines: name, pass = line.split(',') if name == 'whatever': #... </code></pre> <p>And finally to write to the file you've got the <code>write()</code> function.</p> <pre><code>file.write(name + ',' + pass) </code></pre> <p>I think that will help you to complet your programme. :)</p>
1
2016-10-07T21:56:24Z
[ "python", "python-3.x" ]
pygame screen failing to dislpay
39,926,302
<p>I have the following code in Python 3 (and pygame), but the white surface fails to display and I don't understand why. Has it got something to do with where it has been placed? I tried de-indenting, but that didn't work either? The code is as below:</p> <pre><code>import pygame from pygame.locals import* pygame.init() screen=pygame.display.set_mode((800,600)) # Variable to keep our main loop running running = True # Our main loop! while running: # for loop through the event queue for event in pygame.event.get(): # Check for KEYDOWN event; KEYDOWN is a constant defined in pygame.locals, which we imported earlier if event.type == KEYDOWN: # If the Esc key has been pressed set running to false to exit the main loop if event.key == K_ESCAPE: running = False # Check for QUIT event; if QUIT, set running to false elif event.type == QUIT: running = False # Create the surface and pass in a tuple with its length and width surf = pygame.Surface((50, 50)) # Give the surface a color to differentiate it from the background surf.fill((255, 255, 255)) rect = surf.get_rect() screen.blit(surf, (400, 300)) pygame.display.flip() </code></pre>
1
2016-10-07T21:52:32Z
39,926,843
<p>So it does appear that your indentation is wrong.</p> <p>You need to define the surface and update the screen etc. outside of the event loop.</p> <p>At the very least you must move the <code>screen.blit(surf, (400, 300))</code> and <code>pygame.display.flip()</code> outside of the event loop.</p> <p>This is it fixed:</p> <pre><code># Our main loop! while running: # for loop through the event queue for event in pygame.event.get(): # Check for KEYDOWN event; KEYDOWN is a constant defined in pygame.locals, which we imported earlier if event.type == KEYDOWN: # If the Esc key has been pressed set running to false to exit the main loop if event.key == K_ESCAPE: running = False # Check for QUIT event; if QUIT, set running to false elif event.type == QUIT: running = False # Create the surface and pass in a tuple with its length and width surf = pygame.Surface((50, 50)) # Give the surface a color to differentiate it from the background surf.fill((255, 255, 255)) rect = surf.get_rect() screen.blit(surf, (400, 300)) pygame.display.flip() </code></pre>
0
2016-10-07T22:56:52Z
[ "python", "pygame", "surface" ]
Syntax Error near "CHANGE" in sqlite3
39,926,421
<p>I am attempting to execute the following (move a column to be the first one)</p> <pre><code>import sqlite3 db = sqlite3.connect('adatabase.sqlite') c = db.cursor() c.execute('ALTER TABLE tab1 CHANGE COLUMN r r def FIRST') </code></pre> <p>Unfortunately I get this error</p> <pre><code>Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; OperationalError: near "CHANGE": syntax error </code></pre> <p>What could be? Thanks in advance</p>
1
2016-10-07T22:03:18Z
39,926,576
<p><em>SQLite</em> does not support the <code>CHANGE COLUMN</code> feature.</p> <blockquote> <p>Only the <code>RENAME TABLE</code> and <code>ADD COLUMN</code> variants of the <code>ALTER TABLE</code> command are supported</p> </blockquote> <p>See all missing features: <a href="http://www.sqlite.org/omitted.html" rel="nofollow">SQL Features That SQLite Does Not Implement</a></p>
1
2016-10-07T22:21:42Z
[ "python", "mysql", "database", "sqlite", "sqlite3" ]
Access Functions in Dictionary Part 2
39,926,423
<p>As a follow-up to <a href="http://stackoverflow.com/questions/39926137/access-functions-via-dictionary">this question</a>: I have 2 functions that look like this:</p> <pre><code>def abc(a,b): return a+b def cde(c,d): return c+d </code></pre> <p>And I want to assign it to a dictionary like this:</p> <pre><code>functions = {'abc': abc(a,b), 'cde': cde(c,d)} </code></pre> <p>I could do this, but it would break at 'cde':</p> <pre><code>functions = {'abc':abc, 'cde':cde} functions_to_call = ['abc', 'cde'] for f in functions_to_call: a, b = 3, 4 c, d = 1, 2 if f in functions: functions[f](a, b) </code></pre> <p>Also, what if cde took 3 arguments? </p>
1
2016-10-07T22:03:38Z
39,926,532
<p>Make a seperate sequence of <code>args</code> and use the splat operator (<code>*</code>):</p> <pre><code>&gt;&gt;&gt; def ab(a,b): ... return a + b ... &gt;&gt;&gt; def cde(c,d,e): ... return c + d + e ... &gt;&gt;&gt; funcs = {'ab':ab, 'cde':cde} &gt;&gt;&gt; to_call = ['ab','cde'] &gt;&gt;&gt; args = [(1,2),(3,4,5)] &gt;&gt;&gt; for fs, arg in zip(to_call,args): ... print(funcs[fs](*arg)) ... 3 12 </code></pre>
2
2016-10-07T22:15:42Z
[ "python", "list", "function", "python-3.x", "dictionary" ]
Python Slider Value
39,926,455
<p>I have a Scale in my GUI which I'm trying to get continuous values from. Below is my code. </p> <pre><code>from Tkinter import * class Application(Frame): def getVoltage(self): print self.voltage_scale.get() def createWidgets(self): self.voltage_scale = Scale(self) self.voltage_scale["from_"] = 0 self.voltage_scale["to"] = 32 self.voltage_scale["orient"] = "horizontal" self.voltage_scale["command"] = self.getVoltage self.voltage_scale.grid(column=0,row=9) def __init__(self,Master=None) Frame.__init__(self,master) self.createWidgets() self.tn = None root = Tk() app = Application(master=root) app.mainloop() root.destroy() </code></pre> <p>When I run the code above, and start moving my slider, I get an error that says:</p> <pre><code>getVoltage() takes exactly 1 argument, two was given </code></pre> <p>All I'm trying to do is get the value of the slider. Any help would be appreciated.</p>
0
2016-10-07T22:07:35Z
39,926,487
<p><code>def getVoltage(self, event_arg):</code> will fix that. The command of some tk controls is passed some event data as an extra argument</p>
2
2016-10-07T22:10:39Z
[ "python", "user-interface", "tkinter", "tk" ]
Appending (hstack) a comformable array to a matrix returns error
39,926,466
<p>I am trying to <code>np.hstack</code> an array to a matrix. The array has <code>.shape</code> <code>(a,)</code>, the matrix has <code>.shape</code> <code>(a,b)</code>, with <code>a</code> and <code>b</code> integers. I get the error that dimensions do not match (<code>all the input arrays must have same number of dimensions</code>). What should I do to <code>hstack</code> these conformable objects?</p>
0
2016-10-07T22:08:28Z
39,926,500
<p>I think the problem is that what you are calling array is 1-dimensional whereas the matrix is 2-dimensional.</p> <p>Let's say they are called <code>M</code> and <code>N</code>. <code>M.shape</code> gives <code>(a,)</code> (being what you called "an array") and <code>N.shape</code> gives <code>(a,b)</code> (being what you called "a matrix"). If you do <code>M = M.reshape(a, 1)</code> you get a bidimensional array with the same amount of rows as <code>N</code> and <code>np.hstack((M, N))</code> should work.</p> <p>P.S: All the entities you mentioned are arrays, perhaps you meant vector or 1-dimensional array for the first one.</p> <p>EDIT - For example:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a= np.array([1,2,3]) &gt;&gt;&gt; a.shape (3,) &gt;&gt;&gt; b = np.array([[1], [2], [3]]) &gt;&gt;&gt; b.shape (3,1) &gt;&gt;&gt; c = np.hstack((a.reshape(3, 1), b)) &gt;&gt;&gt; c array([[1, 1], [2, 2], [3, 3]]) &gt;&gt;&gt; c.shape (3,2) </code></pre>
1
2016-10-07T22:11:54Z
[ "python", "append" ]
Appending (hstack) a comformable array to a matrix returns error
39,926,466
<p>I am trying to <code>np.hstack</code> an array to a matrix. The array has <code>.shape</code> <code>(a,)</code>, the matrix has <code>.shape</code> <code>(a,b)</code>, with <code>a</code> and <code>b</code> integers. I get the error that dimensions do not match (<code>all the input arrays must have same number of dimensions</code>). What should I do to <code>hstack</code> these conformable objects?</p>
0
2016-10-07T22:08:28Z
39,926,526
<p>Add an <em>extra axis</em> to the first array using <code>None</code> or <code>np.newaxis</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a= np.array([1,2,3]) &gt;&gt;&gt; a.shape (3,) &gt;&gt;&gt; b = np.array([[1], [2], [3]]) &gt;&gt;&gt; b.shape (3, 1) &gt;&gt;&gt; np.hstack((a[:, None], b)) array([[1, 1], [2, 2], [3, 3]]) </code></pre>
1
2016-10-07T22:14:48Z
[ "python", "append" ]
Appending (hstack) a comformable array to a matrix returns error
39,926,466
<p>I am trying to <code>np.hstack</code> an array to a matrix. The array has <code>.shape</code> <code>(a,)</code>, the matrix has <code>.shape</code> <code>(a,b)</code>, with <code>a</code> and <code>b</code> integers. I get the error that dimensions do not match (<code>all the input arrays must have same number of dimensions</code>). What should I do to <code>hstack</code> these conformable objects?</p>
0
2016-10-07T22:08:28Z
39,926,546
<p>Another option is </p> <pre><code>np.transpose(np.asmatrix(a)) </code></pre> <p>before appending.</p>
0
2016-10-07T22:17:30Z
[ "python", "append" ]
Python graphing with numpy
39,926,473
<p>Okay so I'm trying to plot a function with an e to some expression but I keep getting an error at the lines that I have put (##) @ where the error message is</p> <p>TypeError: unsupported operand type(s) for *: 'numpy.ufunc' and 'float'</p> <pre><code>#!C:\Users\msawe\Anaconda3 or C:\Anaconda3\python import numpy as np import matplotlib.pyplot as plt plt.figure (figsize=(10,10), dpi=100) ax = plt.subplot(111) plt.title('Projectile Motion: Goround given by h(x) ', size=24) ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data',0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data',0)) def h(x): "This function will return the y-coordinate for a given x-coordinate launch." ##return 1 - np.exp(-1* x/1000) + 0.28 *( 1 - np.exp(-0.038*x**2))*(1 - np.cos*(20*x**0.2)) X = np.linspace(0, 10, 101, endpoint=True) ##plt.plot(X, h(X), color="black", linewidth=3, linestyle="-", label="h(x)") plt.xlim(0,10) plt.xticks(np.linspace(0,10,11,endpoint=True)) plt.ylim(0,20.0) plt.yticks(np.linspace(0,20,11,endpoint=True)) plt.legend(loc='upper left', frameon=False) plt.savefig("Ch5_P4_lowRes.png",dpi=60) plt.savefig("Ch5_P4_hiRes.png",dpi=200) plt.savefig("Ch5_P4_plotting.pdf",dpi=72) plt.show() </code></pre> <p>If I could just get a general idea on how to make it work that would be great.</p>
-1
2016-10-07T22:09:06Z
39,926,593
<p>Assuming that I'm interpreting your equation correctly, there's a bug in your implementation of <code>np.cos()</code> in your definition of h(x): you wrote <code>np.cos*(...)</code> rather than <code>np.cos(...)</code>. After fixing that, the code is able to plot- hopefully it's giving the right result!</p> <p>This would turn your definition of h(x) from:</p> <pre><code>def h(x): return 1 - np.exp(-1* x/1000) + 0.28 *( 1 - np.exp(-0.038*x**2))*(1 - np.cos*(20*x**0.2)) </code></pre> <p>Into: </p> <pre><code>def h(x): return 1 - np.exp(-1* x/1000) + 0.28 *( 1 - np.exp(-0.038*x**2))*(1 - np.cos(20*x**0.2)) </code></pre> <p>The difference is subtle but important! You can easily check for bugs like this by running successively smaller segments of your code to see which operation is throwing the error- this let me quickly hone in on the <code>np.cos*(...)</code> typo.</p>
0
2016-10-07T22:23:30Z
[ "python", "numpy" ]
multi-core efficiency when doing big computations?
39,926,579
<p>I have a code to find big primes, as it is it checks every odd number, but I wanted to know if I could have it check, for example, every other odd number and have the numbers it skips be checked on a different core.</p>
0
2016-10-07T22:22:01Z
39,927,481
<p>EDIT, added multiprocess and still didn't see a speedup over unthreaded. I don't understand why multiprocessing didn't speed up the code, I'd appreciate feedback. Maybe I didn't write it correctly. You can try playing with it yourself.</p> <p>Code:</p> <pre><code>from multiprocessing import Process, Queue from threading import Thread import time #Function to determine if 'a' is prime, used by all methods def is_prime(a): return all(a % i for i in xrange(2, a)) #Look for primes between 'min_prime' and 'max_prime' min_prime = 3 #must start on odd number! max_prime = 200000 num_threads = 8 times = {} primes = {} ####################### #Multiprocess approach# ####################### def get_primes(q,start_val,num_threads,max_prime): vals = range(start_val,max_prime,num_threads*2) q.put([val for val in vals if is_prime(val)]) start_processes_time = time.time() q = Queue() processes = [] for i in range(num_threads): start = i*2+min_prime p = Process(target=get_primes,args=(q,start,num_threads,max_prime+1,)) processes.append(p) p.start() #Wait for all of them to stop process_primes = set() for p in processes: p.join() process_primes.update(q.get()) times["Processes"] = time.time()-start_processes_time primes["Processes"] = process_primes #################### #Threading approach# #################### class PrimeThread(Thread): __slots__ = ["start_val","num_threads","max_prime","vals","primes"] def __init__(self,start_val,num_threads,max_prime): self.start_val = start_val self.num_threads = num_threads self.stop = max_prime super(PrimeThread, self).__init__() def run(self): self.vals = range(self.start_val,self.stop,self.num_threads*2) self.primes = {val for val in self.vals if is_prime(val)} threads = [] start_thread_time = time.time() for i in range(num_threads): start = i*2+min_prime t = PrimeThread(start,num_threads,max_prime+1) threads.append(t) t.start() thread_primes = set() for t in threads: t.join() thread_primes.update(t.primes) times["Threading"] = time.time()-start_thread_time primes["Threading"] = thread_primes ####################### #Non-threaded approach# ####################### start_no_thread_time = time.time() no_thread_primes = {val for val in range(min_prime,max_prime+1,2) if is_prime(val)} times["Threadless"] = time.time()-start_no_thread_time primes["Threadless"] = no_thread_primes ############### #Compare times# ############### all_found_same_primes = all([p1 == p2 for p1 in primes.values() for p2 in primes.values()]) print "For min_prime=",min_prime,"max_prime=",max_prime,"and",num_threads,"threads:" print "All methods found same primes:",all_found_same_primes,"\n" times = sorted(times.items(), key=lambda x: x[1]) print "\n".join([l+" time: "+str(t) for l,t in times]),"\n" f_m,f_t = times[0] #get fastest method (f_m) and fastest time (f_t) print f_m,"was"," and ".join([str(t/f_t)+" times faster than "+l for l,t in times[1:]]) </code></pre> <p>Output:</p> <pre><code>For min_prime = 3 max_prime = 23 and 8 threads: All methods found same primes: True Threadless time: 2.50339508057e-05 Threading time: 0.00144100189209 Processes time: 0.0272209644318 Threadless was 57.5619047619 times faster than Threading and 1087.36190476 times faster than Processes </code></pre> <p>..</p> <pre><code>For min_prime = 3 max_prime = 200000 and 8 threads: All methods found same primes: True Threadless time: 149.900467873 Processes time: 166.985640049 Threading time: 668.010253906 Threadless was 1.11397677685 times faster than Processes and 4.45635869845 times faster than Threading </code></pre>
0
2016-10-08T00:33:42Z
[ "python", "multithreading", "python-2.7" ]
Sum up the index value in multiple array with pyspark
39,926,603
<p>I have 50 array with float values (<code>50*7</code>). How am I suppose to sum up the 50 arrays on same index to one with PySpark map-reducer function.</p> <p>Example:</p> <pre><code>array1 = {1,2,3,4,5,6,7} array2 = {3,4,2,3,5,6,7} .... </code></pre> <p>the result should be <code>array3 = {4,6,5,7,10,12,14}</code>.</p> <p>This is a project requirement to use PySpark on Map-Reducer platform.</p> <p>Now I can figure out the map part:</p> <pre><code>NUM_SAMPLES = 50 result = sc.parallelize(xrange(0, NUM_SAMPLES)).map(random_generation) </code></pre> <p>The result here contains 50 arrays. Function <code>random_generation</code> gives one array with 7 random numbers.</p> <p>Please anyone can provide me the suggestion on the reduce part.</p>
0
2016-10-07T22:24:35Z
39,928,625
<p>Edit: I think it's easier to use DataFrame.</p> <pre><code>from pyspark.sql import SparkSession spark = SparkSession \ .builder \ .getOrCreate() arrays = [ [1,2,3,4,5,6,7], [3,4,2,3,5,6,7], [1,2,3,4,5,6,7], ] df = spark.createDataFrame(arrays) s = df.groupBy().sum().collect() print s print list(s[0]) </code></pre> <p><strong>Result</strong></p> <pre><code>[Row(sum(_1)=5, sum(_2)=8, sum(_3)=8, sum(_4)=11, sum(_5)=15, sum(_6)=18, sum(_7)=21)] [5, 8, 8, 11, 15, 18, 21] </code></pre>
0
2016-10-08T04:16:46Z
[ "python", "mapreduce", "pyspark" ]
Numpy reshape acts different on copied vs. uncopied arrays
39,926,628
<p>I've come across seemingly inconsistent results when flattening certain numpy arrays with numpy.reshape. Sometimes if I reshape an array it returns a 2D array with one row, whereas if I first copy the array then do the exact same operation, it returns a 1D array. </p> <p>This seems to happen primarily when combining numpy arrays with scipy arrays, and creates alignment problems when I want to later multiply the flattened array by a matrix.</p> <p>For example, consider the following code:</p> <pre><code>import numpy as np import scipy.sparse as sps n = 10 A = np.random.randn(n,n) I = sps.eye(n) X = I+A x1 = np.reshape(X, -1) x2 = np.reshape(np.copy(X), -1) print 'x1.shape=', x1.shape print 'x2.shape=', x2.shape </code></pre> <p>When run it prints:</p> <pre><code>x1.shape= (1, 100) x2.shape= (100,) </code></pre> <p>The same thing happens with numpy.flatten(). What is going on here? Is this behavior intentional?</p>
3
2016-10-07T22:28:31Z
39,926,675
<p>You added together a sparse matrix object and a normal ndarray:</p> <pre><code>X = I+A </code></pre> <p>The result is a dense <em>matrix</em> object, an instance of <code>np.matrix</code>, not a normal ndarray.</p> <p>This:</p> <pre><code>np.reshape(X, -1) </code></pre> <p>ends up returning a matrix, which can't be less than 2D.</p> <p>This:</p> <pre><code>np.reshape(np.copy(X), -1) </code></pre> <p>makes a normal ndarray in <code>np.copy(X)</code>, so you get a 1D output from <code>np.reshape</code>.</p> <p>Be very careful at all times about whether you're dealing with sparse matrices, dense matrices, or standard ndarrays. Avoid <code>np.matrix</code> whenever possible.</p>
5
2016-10-07T22:36:20Z
[ "python", "arrays", "numpy", "scipy" ]
Create an instance of a class from a type class string like 'containers.Room'?
39,926,638
<p>I'm new to programming and I've chosen Python. I've gone through all of learn python the hard way, I've coded my own 'choose your own adventure game' and now I'm moving on to creating something more akin to a MOO. </p> <p>I've structured my objects database to be very simple (everything in the game will be an object, and a separate attributes database will help customize things). Current Object structure is like this:</p> <p>objectid, name, typeclass, locationid</p> <p>locationid is a foreign key back to the same objectid, that way objects can belong to a room, or a player.</p> <p>My question comes with how I want to have typeclass set up. Currently I want to store a string in there like: containers.Room. When I pull the information from the database (or create a new room), I want to be able to make an instance of the class Room() contained in a separate python script called containers. I know about being to do an from containers import room, but I don't know how to dynamically do it from a stored string.</p> <p>Thank you in advance to anyone that may know and share the answer with me!</p> <p><strong>edit for clarity</strong> (I rambled...)</p> <p>I want to pull a string from my database ("module.Class"), import that module and class, and create an instance of said class.</p> <p><strong>edit2</strong> Using sqlite, here is my creation command. At the end I want to return an instance of the typeclass.</p> <pre><code>def create(self, **args): #requires name=string and typeclass=string. no locationid for rooms #connect to the sqlite db and create a cursor for commands conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() #probably a better way to do this, but this is what I came up with columns = [] values = [] for k, v in args.iteritems(): #iterate through arguments, if the column ends in 'id' assume int columns.append(k) if k[-2:] == "id": values.append("%s" % v) else: values.append(("'%s'" % v)) #join columsn and rows and plug them into the query cols = ', '.join(columns) rows = ', '.join(values) query = "INSERT INTO objects_db (%s) VALUES (%s)" % (cols, rows) #execute the query, commit, and close the connection. cursor.execute(query) conn.commit() conn.close() &gt;&gt;&gt; stuff here to import args['typeclass'] &lt;&lt;&lt; </code></pre> <p>So I would be able to have a line like:</p> <p>myobj = create(name="my object", typeclass="objects.things.Thing")</p> <p>That would create a 'my object' in the database, and the 'myobj' variable would be an instance of the class Thing, found in the objects folder and things.py file.</p>
-1
2016-10-07T22:29:33Z
39,927,259
<p>So I figured out that my issue was due to trying to import modules from siblings when I was directly running my db.py script to test it.</p> <p>I created a main.py file in my root directory for the project, allowing me to do something like this:</p> <pre><code> typeclass = args['typeclass'].split('.') import_path = "objects.%s" % typeclass[0] _temp = importlib.import_module(import_path) myobj = getattr(_temp, typeclass[1]) return myobj(args['name'], args['locationid']) </code></pre> <p>The create function I'm working on is only used for objects, so I was able to assume an objects folder. So I just needed the things.Thing part, so I was able to split it, import the script and get the attribute and run from there.</p>
0
2016-10-07T23:53:34Z
[ "python", "python-2.7" ]
UnboundLocalError: local variable 'number1' referenced before assignment
39,926,640
<p>I am getting an error in line 2 saying that i have an unboundLocal error. can anyone explain to me how to fix this?</p> <pre><code> def main(): number1=getNumber1(number1) number2=getNumber2(number2) userIntro='' printInfo=0.0 answer=0.0 #intro module welcomes the user def userIntro(): print('hello welcome to my maximum value calculator') print('today we will evaluate two number and display the greater one') #this module gets the value of number1 def getNumber1(number1): number1=print(input('Enter the value of number1')) return (getNumber1) #this module gets the value of number2 def getnumber2(number2): number2=print(input('Enter the value of number2')) return (getNumber2) #this module takes the values of number1,number2 and displays the greater value def printInfo(number1,number2,answer): answer=max(number1,number2) return (answer) main() </code></pre>
-2
2016-10-07T22:29:56Z
39,926,677
<p><code>number1</code> isn't defined until you create it - you can't pass it to another function while defining it. Seems like you need a simpler function that gets the <strong>name</strong> you want to assign to:</p> <pre><code>def main(): number1 = getNumber('number1') number2 = getNumber('number2') def getNumber(name): return input('Enter the value of ' + name)) </code></pre>
1
2016-10-07T22:36:34Z
[ "python", "python-2.7", "python-3.x" ]
if statement in subprocess.Popen
39,926,662
<p>I'm trying to run bash code via python. Normal statements (netstat, for example) work. If functions like the one below, however, don't. What should I change in order to run the following code correctly? Thanks in advance</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; import subprocess &gt;&gt;&gt; &gt;&gt;&gt; os.setenv['a']='test' &gt;&gt;&gt; _c = 'if [ "$a" == "test" ]; then echo $a; fi' &gt;&gt;&gt; print(subprocess.Popen(_c, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')) /bin/sh: 1: [: anto: unexpected operator </code></pre>
0
2016-10-07T22:33:30Z
39,927,295
<p>The command you are trying to run in the subprocess is following the <code>bash</code> shell syntax, where the string equality test is performed via <code>==</code>. Now, on Unix with shell=True, the shell defaults to <code>/bin/sh</code> where instead the equality test is performed via a simple <code>=</code>. The two options you have here are:</p> <ol> <li>follow <code>sh</code> syntax in your script</li> <li>explicitly call '/bin/bash' as the executable to be run by adding <code>executable='/bin/bash'</code> to the Popen</li> </ol> <p>As for option (1), replace <code>_c</code> as follows and it should work fine:</p> <pre><code>import os, subprocess m_env = os.environ m_env['a'] = "test" _c = 'if [ "$a" = "test" ]; then echo $a; fi' print(subprocess.Popen(_c, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')) </code></pre> <p>That prints out "test".</p>
1
2016-10-07T23:58:26Z
[ "python", "bash", "if-statement", "subprocess" ]
Python2.7 how do I use multiples variables in a loop?
39,926,676
<p>I'm making my own game with Python2.7 through the pygame libraby. It's a 1v1 combat game where players use the same keyboard.</p> <p>The game works in a main loop that is repeated 60times per second, every time the loop is executed, it calculates lots of things e.g the position, problem is that I have 2 players, so I have to write the lines two times.</p> <blockquote> <p>Example here:</p> <p>if p1direction == 'right' and p1XS &lt; p1Attributes[1]: p1XS += p1Attributes[0]</p> <p>and:</p> <p>if p2direction == 'right' and p2XS &lt; p2Attributes[1]: p2XS += p2Attributes[0]</p> </blockquote> <p>See the differences p1 and p2, they are variables that belongs to Player 1 and Player 2 respectively.</p> <p>I just want to find a solution to not write every time the same lines just for p2. I was thinking about the for function so I can even add players easly but I don't know how to do it in this case...</p> <p>Can someone help me ? :) Please</p>
0
2016-10-07T22:36:32Z
39,926,733
<p>Create a class player. Then add the attributes of each player to the class. Instantiate your class with player 1 and 2. </p> <pre><code>class Player(): direction = "right" etc. def shoot(self): if self.direction == "right" shoot_right() playerOne = Player() playerTwo = Player() direction = playerOne.direction </code></pre> <p>If you haven't used classes yet, I wouldn't recommend using them though. Inheritance can get pretty nasty...</p> <p>Hope that helped, Narusan</p> <p>EDIT: If you haven't used classes in Python yet, I recommend catching up there first and then continuing your game development. I have programmed several games in pygame as well, and classes come in very hand. In fact, it is almost impossible to create pygame games without using proper classes (or endless if-clauses and for-loops that will make everything super slow).</p> <p>Wish you all the best of luck</p>
2
2016-10-07T22:43:12Z
[ "python", "loops", "variables", "pygame" ]
Python2.7 how do I use multiples variables in a loop?
39,926,676
<p>I'm making my own game with Python2.7 through the pygame libraby. It's a 1v1 combat game where players use the same keyboard.</p> <p>The game works in a main loop that is repeated 60times per second, every time the loop is executed, it calculates lots of things e.g the position, problem is that I have 2 players, so I have to write the lines two times.</p> <blockquote> <p>Example here:</p> <p>if p1direction == 'right' and p1XS &lt; p1Attributes[1]: p1XS += p1Attributes[0]</p> <p>and:</p> <p>if p2direction == 'right' and p2XS &lt; p2Attributes[1]: p2XS += p2Attributes[0]</p> </blockquote> <p>See the differences p1 and p2, they are variables that belongs to Player 1 and Player 2 respectively.</p> <p>I just want to find a solution to not write every time the same lines just for p2. I was thinking about the for function so I can even add players easly but I don't know how to do it in this case...</p> <p>Can someone help me ? :) Please</p>
0
2016-10-07T22:36:32Z
39,926,778
<p>How about storing your variables(for example p1direction and p2direction) in a vector(player_directions) indexed by the player number and using a loop access it, for example:</p> <pre><code>number_of_players = 2 playersXS = function_that_fills_playersXS() # return a vector containing your p1XS and p2XS variables in a vector for player_number in xrange(number_of_players): if player_directions[player_number]=='right' and playersXS[player_number]&lt; Attributes[player_number][1]: playersXS[player_number]+=Attributes[player_number][0] </code></pre>
0
2016-10-07T22:50:24Z
[ "python", "loops", "variables", "pygame" ]
How do I add mass comments into Windows Command prompt?
39,926,717
<p>I have a lot of text I would like to add as a comment. For example, I want to put the enitre help section of CHKDSK:</p> <pre> Checks a disk and displays a status report. CHKDSK [volume[[path]filename]]] [/F] [/V] [/R] [/X] [/I] [/C] [/L[:size]] [/B] [/scan] [/spotfix] volume Specifies the drive letter (followed by a colon), mount point, or volume name. filename FAT/FAT32 only: Specifies the files to check for fragmentation. /F Fixes errors on the disk. /V On FAT/FAT32: Displays the full path and name of every file on the disk. On NTFS: Displays cleanup messages if any. /R Locates bad sectors and recovers readable information (implies /F, when /scan not specified). /L:size NTFS only: Changes the log file size to the specified number of kilobytes. If size is not specified, displays current size. /X Forces the volume to dismount first if necessary. All opened handles to the volume would then be invalid (implies /F). /I NTFS only: Performs a less vigorous check of index entries. /C NTFS only: Skips checking of cycles within the folder structure. /B NTFS only: Re-evaluates bad clusters on the volume (implies /R) /scan NTFS only: Runs a online scan on the volume /forceofflinefix NTFS only: (Must be used with "/scan") Bypass all online repair; all defects found are queued for offline repair (i.e. "chkdsk /spotfix"). /perf NTFS only: (Must be used with "/scan") Uses more system resources to complete a scan as fast as possible. This may have a negative performance impact on other tasks running on the system. /spotfix NTFS only: Runs spot fixing on the volume /sdcleanup NTFS only: Garbage collect unneeded security descriptor data (implies /F). /offlinescanandfix Runs an offline scan and fix on the volume. /freeorphanedchains FAT/FAT32/exFAT only: Frees any orphaned cluster chains instead of recovering their contents. /markclean FAT/FAT32/exFAT only: Marks the volume clean if no corruption was detected, even if /F was not specified. The /I or /C switch reduces the amount of time required to run Chkdsk by skipping certain checks of the volume. </pre> <p>However, it is very annoying (and time-consuming) to have to put <code>rem</code> tags on the front of every line of code, like:</p> <pre> rem Checks a disk and displays a status report. rem CHKDSK [volume[[path]filename]]] [/F] [/V] [/R] [/X] [/I] [/C] [/L[:size]] [/B] [/scan] [/spotfix] rem volume Specifies the drive letter (followed by a colon), rem mount point, or volume name. rem filename FAT/FAT32 only: Specifies the files to check for rem fragmentation. rem /F Fixes errors on the disk. rem /V On FAT/FAT32: Displays the full path and name of every rem file on the disk. rem On NTFS: Displays cleanup messages if any. rem /R Locates bad sectors and recovers readable information rem (implies /F, when /scan not specified). rem /L:size NTFS only: Changes the log file size to the specified rem number of kilobytes. If size is not specified, displays rem current size. rem /X Forces the volume to dismount first if necessary. rem All opened handles to the volume would then be invalid rem (implies /F). rem /I NTFS only: Performs a less vigorous check of index rem entries. rem /C NTFS only: Skips checking of cycles within the folder rem structure. rem /B NTFS only: Re-evaluates bad clusters on the volume rem (implies /R) rem /scan NTFS only: Runs a online scan on the volume rem /forceofflinefix NTFS only: (Must be used with "/scan") rem Bypass all online repair; all defects found rem are queued for offline repair (i.e. "chkdsk /spotfix"). rem /perf NTFS only: (Must be used with "/scan") rem Uses more system resources to complete a scan as fast as rem possible. This may have a negative performance impact on rem other tasks running on the system. rem /spotfix NTFS only: Runs spot fixing on the volume rem /sdcleanup NTFS only: Garbage collect unneeded security descriptor rem data (implies /F). rem /offlinescanandfix Runs an offline scan and fix on the volume. rem /freeorphanedchains FAT/FAT32/exFAT only: Frees any orphaned cluster chains rem instead of recovering their contents. rem /markclean FAT/FAT32/exFAT only: Marks the volume clean if no rem corruption was detected, even if /F was not specified. rem The /I or /C switch reduces the amount of time required to run Chkdsk by rem skipping certain checks of the volume. </pre> <p>Is there a way I could mass comment code (like <code>""" comment here, can be multiple lines"""</code>in Python?)</p>
0
2016-10-07T22:41:08Z
39,927,903
<p>This is easy to do if you use Vim:</p> <ol> <li>Move to the first column of the first line you want to comment.</li> <li>Press <code>&lt;C-v&gt;</code> (<kbd>Ctrl</kbd>+<kbd>V</kbd>) to enter block select mode.</li> <li>Move the selection to the first column of the last line you want to comment.</li> <li>Type <code>Irem&lt;esc&gt;</code> (Insert, type rem, back to normal mode).</li> </ol> <p>Alternatively, since you seem to be familiar with Python, you could pipe it through this script, then copy the output:</p> <pre><code>import sys for line in sys.stdin: sys.stdout.write("rem " + line) </code></pre> <p><code>CHKDSK /? | python3 comment.py</code></p>
0
2016-10-08T01:52:31Z
[ "python", "windows", "comments", "command-prompt" ]
Python can't find setuptools
39,926,760
<p>I got the following ImportError as i tried to setup.py install a package:</p> <pre><code>Traceback (most recent call last): File "setup.py", line 4, in &lt;module&gt; from setuptools import setup, Extension ImportError: No module named setuptools </code></pre> <p>This happens although setuptools is already installed:</p> <pre><code>amir@amir-debian:~$ sudo apt-get install python-setuptools [sudo] password for amir: Reading package lists... Done Building dependency tree Reading state information... Done python-setuptools is already the newest version. 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. </code></pre> <p>Why can't python find the setuptools module? </p>
0
2016-10-07T22:48:03Z
39,926,820
<p>It's possible you have multiple python versions installed on your system. For example if you installed your python from source, and then again with apt-get. Apt-get will install to the default python version. Make sure you are being consistent. </p> <p>Potentially using pip install setuptools could solve your problem.</p> <p>Try these commands:</p> <pre><code>$which python /usr/bin/python $python --version Python 2.7.12 </code></pre> <p>Making sure that the output matches your expectations.</p> <p>It may be worth removing previous installations and starting over as this answer suggests:</p> <p><a href="http://stackoverflow.com/questions/14426491/python-3-importerror-no-module-named-setuptools">Python 3: ImportError &quot;No Module named Setuptools&quot;</a></p>
1
2016-10-07T22:55:03Z
[ "python", "python-2.7", "setuptools" ]
"only length-1 arrays can be converted to Python scalars"-error with float conversion-function
39,926,825
<p>When running this program, I receive the error "TypeError: only length-1 arrays can be converted to Python scalars", specifically referring to line 9, where the x1-variable is assigned. </p> <p>I'm kind of clueless here what it means in this context. I worked with a very similar piece of code for a previous assignment, where it all worked fine. I took in a vector as an argument to the function and computed all the values simultaneously. </p> <p>Note: After I removed the floating it seems to work fine, but I have no clue why. Can anyone explain?</p> <pre><code>import matplotlib.pyplot as plt import numpy as np g = 9.78 p = 1000 h = 50 s = 7.9 * 10**-2 def water_wave_speed(l): x1 = float(g * l/(2 * np.pi)) x2 = 1 + s * float((4 * np.pi**2)/(p * g * l**2)) x3 = float((2 * np.pi * h)/l) c = np.sqrt(x1 * x2 * np.tanh(x3)) return c l_values = np.linspace(0.001, 0.1, 10) c_values = water_wave_speed(l_values) plt.plot(l_values, c_values) plt.show() </code></pre>
0
2016-10-07T22:55:30Z
39,926,878
<p>Drop all of those <code>float</code> calls and your code should work (as <em>floats</em>). You're trying to coerce numpy arrays into single float values which isn't going to work.</p>
2
2016-10-07T23:01:19Z
[ "python", "arrays", "numpy", "vector" ]
Error running endpointscfg.py get_swagger_spec
39,926,853
<p>I am trying to build a project using Google Cloud Endpoints, following this guide: <a href="https://cloud.google.com/endpoints/docs/frameworks/python/quickstart-frameworks-python" rel="nofollow">Quickstart for Cloud Endpoints Frameworks on App Engine</a>.</p> <p>I am stuck at the step of generating the OpenAPI configuration file, where I need to run this command: </p> <p><strong>Attempt One</strong></p> <pre><code>$ lib/endpoints/endpointscfg.py get_swagger_spec main.EchoApi --hostname your-service.appspot.com </code></pre> <p>I get this error:</p> <pre><code>-bash: lib/endpoints/endpointscfg.py: Permission denied </code></pre> <p><strong>Attempt Two</strong></p> <p>I have tried the same command with <code>sudo</code>, which returned this error:</p> <pre><code>sudo: lib/endpoints/endpointscfg.py: command not found </code></pre> <p><strong>Attempt Three</strong></p> <p>I have tried to <code>cd lib/endpoints</code> to run the command from the same folder as <code>endpointscfg.py</code> file:</p> <pre><code>$ cd lib/endpoints $ endpointscfg.py get_swagger_spec main.EchoApi --hostname your-service.appspot.com usage: /Users/myName/google-cloud-sdk/platform/google_appengine/endpointscfg.py [-h] {get_client_lib, get_discovery_doc} ... /Users/myName/google-cloud-sdk/platform/google_appengine/endpointscfg.py: error: argument {get_client_lib, get_discovery_doc}: invalid choice: 'get_swagger_spec' (choose from 'get_client_lib', 'get_discovery_doc') </code></pre> <p><strong>Attempt Four</strong></p> <p>Running it with python returns a different kind of issue:</p> <pre><code>$ python lib/endpoints/endpointscfg.py get_swagger_spec main.EchoApi --hostname your-service.appspot.com Traceback (most recent call last): File "lib/endpoints/endpointscfg.py", line 59, in &lt;module&gt; import _endpointscfg_setup # pylint: disable=unused-import File "/Users/myName/lab/python-docs-samples/appengine/standard/endpoints-frameworks-v2/echo/lib/endpoints/_endpointscfg_setup.py", line 98, in &lt;module&gt; _SetupPaths() File "/Users/myName/lab/python-docs-samples/appengine/standard/endpoints-frameworks-v2/echo/lib/endpoints/_endpointscfg_setup.py", line 94, in _SetupPaths from google.appengine.ext import vendor ImportError: No module named appengine.ext </code></pre>
1
2016-10-07T22:58:05Z
39,926,959
<p>Rather than running it directly, try running it with Python, a la:</p> <pre><code>python lib/endpoints/endpointscfg.py get_swagger_spec main.EchoApi --hostname your-service.appspot.com </code></pre> <p>Tried that and it just worked for me. I'll try and make this better (either by fixing the docs or applying some fix in the repo), but that might get you what you need in the interim.</p>
0
2016-10-07T23:11:55Z
[ "python", "google-app-engine", "google-cloud-platform", "google-cloud-endpoints", "google-cloud-sdk" ]
Error running endpointscfg.py get_swagger_spec
39,926,853
<p>I am trying to build a project using Google Cloud Endpoints, following this guide: <a href="https://cloud.google.com/endpoints/docs/frameworks/python/quickstart-frameworks-python" rel="nofollow">Quickstart for Cloud Endpoints Frameworks on App Engine</a>.</p> <p>I am stuck at the step of generating the OpenAPI configuration file, where I need to run this command: </p> <p><strong>Attempt One</strong></p> <pre><code>$ lib/endpoints/endpointscfg.py get_swagger_spec main.EchoApi --hostname your-service.appspot.com </code></pre> <p>I get this error:</p> <pre><code>-bash: lib/endpoints/endpointscfg.py: Permission denied </code></pre> <p><strong>Attempt Two</strong></p> <p>I have tried the same command with <code>sudo</code>, which returned this error:</p> <pre><code>sudo: lib/endpoints/endpointscfg.py: command not found </code></pre> <p><strong>Attempt Three</strong></p> <p>I have tried to <code>cd lib/endpoints</code> to run the command from the same folder as <code>endpointscfg.py</code> file:</p> <pre><code>$ cd lib/endpoints $ endpointscfg.py get_swagger_spec main.EchoApi --hostname your-service.appspot.com usage: /Users/myName/google-cloud-sdk/platform/google_appengine/endpointscfg.py [-h] {get_client_lib, get_discovery_doc} ... /Users/myName/google-cloud-sdk/platform/google_appengine/endpointscfg.py: error: argument {get_client_lib, get_discovery_doc}: invalid choice: 'get_swagger_spec' (choose from 'get_client_lib', 'get_discovery_doc') </code></pre> <p><strong>Attempt Four</strong></p> <p>Running it with python returns a different kind of issue:</p> <pre><code>$ python lib/endpoints/endpointscfg.py get_swagger_spec main.EchoApi --hostname your-service.appspot.com Traceback (most recent call last): File "lib/endpoints/endpointscfg.py", line 59, in &lt;module&gt; import _endpointscfg_setup # pylint: disable=unused-import File "/Users/myName/lab/python-docs-samples/appengine/standard/endpoints-frameworks-v2/echo/lib/endpoints/_endpointscfg_setup.py", line 98, in &lt;module&gt; _SetupPaths() File "/Users/myName/lab/python-docs-samples/appengine/standard/endpoints-frameworks-v2/echo/lib/endpoints/_endpointscfg_setup.py", line 94, in _SetupPaths from google.appengine.ext import vendor ImportError: No module named appengine.ext </code></pre>
1
2016-10-07T22:58:05Z
40,112,797
<p>I had the exact same problem and tried the same things. What worked for me was:</p> <pre><code>chmod +x lib/endpoints/endpointscfg.py </code></pre> <p>Then running the command again.</p>
0
2016-10-18T15:52:36Z
[ "python", "google-app-engine", "google-cloud-platform", "google-cloud-endpoints", "google-cloud-sdk" ]
How do I split this into maybe 2 or 3 functions?
39,926,911
<p>I was just wondering how do I split this into different functions say like maybe 2 or 3 functions? I'm not that good with passing parameters with functions yet. Would you recommend doing that or should I keep it the way it is in one function since it's a while loop? By the way it's for a beginner programming class so that's why its pretty long.</p> <pre><code>def sumOfDoublePlace(userChoice): lenChecker = len(str(userChoice)) counter = 0 sumNumber = 0 userChoice = int(userChoice) while counter &lt; lenChecker-1: counter += 1 endDigit, userChoice = divmod(userChoice, 10) if counter % 2 == 0: evenNumber = endDigit * 2 if evenNumber &lt; 10: sumNumber = sumNumber + evenNumber else: oddDigit = endDigit % 10 firstDigit = endDigit // 10 oddSum = oddDigit + firstDigit sumNumber = sumNumber + oddSum else: sumNumber = sumNumber + endDigit if sumNumber % 10 == 0: print('This card is valid') else: print('This card is invalid') </code></pre>
0
2016-10-07T23:05:25Z
39,927,114
<p>Overall, I think this should be a single routine. However, you are taking a somewhat tortuous path to the solution. You're doing a <em>lot</em> of work to pull digits out of the integer version of the card number, when they're perfectly accessible in the original text.</p> <p>Here's a start on accessing the string positions you need:</p> <pre><code>def isValidCardNumber(cardNumber): num_len = len(cardNumber) last = int(cardNumber[-1]) # grab the last digit; convert to integer odds = cardNumber[0:-1:2] # positions 0, 2, 4, ... last-1 evens = cardNumber[1:-1:2] # positions 1, 3, 5, ... last-1 # For each list of digits, make a list of their integer equivalents. # ... and immediately take the sum of those integers. odd_sum = sum([int(digit) for digit in odds]) even_sum = sum([int(digit) for digit in evens]) </code></pre> <p>I leave the rest of this to you. :-)</p>
2
2016-10-07T23:32:48Z
[ "python", "python-3.x" ]
for loop iterates over first letter only
39,926,952
<p>My loop seems to iterate over the first letter and then breaks though it's supposed to iterate through each letter in the secretWord, for example, the code bellow is supposed to print out "_pp_e" but instead it only prints "_". I don't understand, what's the problem with that code??</p> <pre><code>def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' # FILL IN YOUR CODE HERE... for letter in secretWord: if letter in lettersGuessed: return letter else: return '_' print(getGuessedWord("apple", ['e', 'i', 'k', 'p', 'r', 's'])) </code></pre>
0
2016-10-07T23:10:35Z
39,926,974
<p>You <code>return</code> from the function in the first iteration. <code>return</code> <strong>ends</strong> a function, there and then, so the <code>for</code> loop won't continue either.</p> <p>You need to build up your return value <em>in the function itself</em>. Build up the resulting string one character at a time, by using a list to hold all the characters first then joining those together into one string at the end:</p> <pre><code>def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' guessed = [] for letter in secretWord: if letter in lettersGuessed: guessed.append(letter) else: guessed.append('_') return ''.join(guessed) </code></pre> <p>If you are feeling adventurous, you could even make that a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> and do all the work in one line:</p> <pre><code>def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' return ''.join([l if l in lettersGuessed else '_' for l in secretWord]) </code></pre> <p>Either version produces the expected output:</p> <pre><code>&gt;&gt;&gt; print(getGuessedWord("apple", ['e', 'i', 'k', 'p', 'r', 's'])) _pp_e </code></pre>
2
2016-10-07T23:13:46Z
[ "python", "debugging", "for-loop" ]
for loop iterates over first letter only
39,926,952
<p>My loop seems to iterate over the first letter and then breaks though it's supposed to iterate through each letter in the secretWord, for example, the code bellow is supposed to print out "_pp_e" but instead it only prints "_". I don't understand, what's the problem with that code??</p> <pre><code>def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' # FILL IN YOUR CODE HERE... for letter in secretWord: if letter in lettersGuessed: return letter else: return '_' print(getGuessedWord("apple", ['e', 'i', 'k', 'p', 'r', 's'])) </code></pre>
0
2016-10-07T23:10:35Z
39,927,010
<p>The return keyword exits the calling function. This should do the trick: </p> <pre><code>def getGuessedWord(secretWord, lettersGuessed): result = '' for letter in secretWord: if letter in lettersGuessed: result += letter else: result += '_' return result print(getGuessedWord("apple", ['e', 'i', 'k', 'p', 'r', 's'])) </code></pre> <p>Here, you start with an empty string as the result and either append a letter (if it was included in the list) or an underscore (if it was not), then return the result string.</p>
0
2016-10-07T23:17:53Z
[ "python", "debugging", "for-loop" ]
Selecting multiple elements from array python
39,927,044
<p>this is a pretty basic question but here goes:</p> <p>I would like to create an array and then would like to compare a user input to those elements within the array.</p> <p>If one element is matched then function 1 would run. If two elements were matched in the array the an alternative function would run and so on and so forth.</p> <p>Currently i can only use an IF statement with no links to the array as follows:</p> <pre><code>def stroganoff(): print ("You have chosen beef stroganoff") return def beef_and_ale_pie(): print ("You have chosen a beef and ale pie") return def beef_burger(): print ("You have chosen a beef burger") return ingredients = ['beef','mushrooms','ale','onions','steak','burger'] beef = input("Please enter your preferred ingredients ") if "beef" in beef and "mushrooms" in beef: stroganoff() elif "beef" in beef and "ale" in beef: beef_and_ale_pie() elif "beef" in beef and "burger" in beef: beef_burger() </code></pre> <p>As said, this is basic stuff for some of you but thank you for looking!</p>
0
2016-10-07T23:21:50Z
39,927,108
<p>So I understand your question such that you want to know, how many of your <code>ingredients</code> are entered by the user:</p> <pre><code>ingredients = {'beef','mushrooms','ale','onions','steak','burger'} # assume for now the inputs are whitespace-separated: choices = input("Please enter your preferred ingredients ").split() num_matches = len(ingredients.intersection(choices)) print('You chose', num_matches, 'of our special ingredients.') </code></pre>
0
2016-10-07T23:32:14Z
[ "python", "arrays", "python-3.x" ]
Selecting multiple elements from array python
39,927,044
<p>this is a pretty basic question but here goes:</p> <p>I would like to create an array and then would like to compare a user input to those elements within the array.</p> <p>If one element is matched then function 1 would run. If two elements were matched in the array the an alternative function would run and so on and so forth.</p> <p>Currently i can only use an IF statement with no links to the array as follows:</p> <pre><code>def stroganoff(): print ("You have chosen beef stroganoff") return def beef_and_ale_pie(): print ("You have chosen a beef and ale pie") return def beef_burger(): print ("You have chosen a beef burger") return ingredients = ['beef','mushrooms','ale','onions','steak','burger'] beef = input("Please enter your preferred ingredients ") if "beef" in beef and "mushrooms" in beef: stroganoff() elif "beef" in beef and "ale" in beef: beef_and_ale_pie() elif "beef" in beef and "burger" in beef: beef_burger() </code></pre> <p>As said, this is basic stuff for some of you but thank you for looking!</p>
0
2016-10-07T23:21:50Z
39,927,142
<p>You may do something like:</p> <pre><code># Dictionary to map function to execute with count of matching words check_func = { 0: func_1, 1: func_2, 2: func_3, } ingredients = ['beef','mushrooms','ale','onions','steak','burger'] user_input = input() # Convert user input string to list of words user_input_list = user_input.split() # Check for the count of matching keywords count = 0 for item in user_input_list: if item in ingredients: count += 1 # call the function from above dict based on the count check_func[count]() </code></pre>
0
2016-10-07T23:36:48Z
[ "python", "arrays", "python-3.x" ]
Selecting multiple elements from array python
39,927,044
<p>this is a pretty basic question but here goes:</p> <p>I would like to create an array and then would like to compare a user input to those elements within the array.</p> <p>If one element is matched then function 1 would run. If two elements were matched in the array the an alternative function would run and so on and so forth.</p> <p>Currently i can only use an IF statement with no links to the array as follows:</p> <pre><code>def stroganoff(): print ("You have chosen beef stroganoff") return def beef_and_ale_pie(): print ("You have chosen a beef and ale pie") return def beef_burger(): print ("You have chosen a beef burger") return ingredients = ['beef','mushrooms','ale','onions','steak','burger'] beef = input("Please enter your preferred ingredients ") if "beef" in beef and "mushrooms" in beef: stroganoff() elif "beef" in beef and "ale" in beef: beef_and_ale_pie() elif "beef" in beef and "burger" in beef: beef_burger() </code></pre> <p>As said, this is basic stuff for some of you but thank you for looking!</p>
0
2016-10-07T23:21:50Z
39,928,296
<p>Since you only can work with IF statements </p> <pre><code>beef=input().split() #this splits all the characters when they're space separated #and makes a list of them </code></pre> <p>you can use your <code>"beef" in beef and "mushrooms" in beef</code> and it should run as you expected it to</p>
0
2016-10-08T03:10:45Z
[ "python", "arrays", "python-3.x" ]
Indentation error - python
39,927,079
<p>I am unsure what is wrong with my code. I am trying to write a program that finds the prime factorization of a number, and iterates through numbers. My code is </p> <pre><code>import math import time def primfacfind(n1,n2): while n1 &lt; n2: n = n1 primfac=[] time_start = time.clock() def primes(n): sieve = [True] * n for i in xrange(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1) return [2] + [i for i in xrange(3,n,2) if sieve[i]] print primes(n) def factfind(lsp,n): #finds factors of n among primes for i in lsp: if n%i==0: primfac.append(i) else: i+=1 factfind(primes(n),n) print primfac def simplify(lsp): for i in lsp: if lsp.count(i) &gt; 1: i+=1 #should simplify to 3^2 instead of 3,3; unfinished time_end = time.clock() time_elapsed = time_end - time_start print time_elapsed n1+=1 print primfacfind(6,15) </code></pre> <p>The error given is </p> <pre><code>Traceback (most recent call last): File "python", line 15 sieve = [True] * n ^ IndentationError: expected an indented block </code></pre> <p>I've checked over my indentation again and again, and I am unsure as to what is wrong. The program worked when it was not in the overall function and while loop, but I don't see how that should make a difference. It would be appreciated if the answer code was as simple as possible to understand, as I am somewhat new to python. </p> <p>Any help with this error would be appreciated. Thanks!</p>
0
2016-10-07T23:26:12Z
39,927,131
<p>I put that code in my editor and it compiled just fine. So I went to line 12 where you have <code>sieve = [True] * n</code> and got rid of the indentation so it was indented the same as the line above it <code>def primes(n):</code> and I was able to recreate your error. </p> <p>Perhaps try and add an additional indentation than you think. You can also try Enthought Canopy which is free if you go to a university if you want a different editor. </p>
-1
2016-10-07T23:35:48Z
[ "python", "compiler-errors", "indentation" ]
Indentation error - python
39,927,079
<p>I am unsure what is wrong with my code. I am trying to write a program that finds the prime factorization of a number, and iterates through numbers. My code is </p> <pre><code>import math import time def primfacfind(n1,n2): while n1 &lt; n2: n = n1 primfac=[] time_start = time.clock() def primes(n): sieve = [True] * n for i in xrange(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1) return [2] + [i for i in xrange(3,n,2) if sieve[i]] print primes(n) def factfind(lsp,n): #finds factors of n among primes for i in lsp: if n%i==0: primfac.append(i) else: i+=1 factfind(primes(n),n) print primfac def simplify(lsp): for i in lsp: if lsp.count(i) &gt; 1: i+=1 #should simplify to 3^2 instead of 3,3; unfinished time_end = time.clock() time_elapsed = time_end - time_start print time_elapsed n1+=1 print primfacfind(6,15) </code></pre> <p>The error given is </p> <pre><code>Traceback (most recent call last): File "python", line 15 sieve = [True] * n ^ IndentationError: expected an indented block </code></pre> <p>I've checked over my indentation again and again, and I am unsure as to what is wrong. The program worked when it was not in the overall function and while loop, but I don't see how that should make a difference. It would be appreciated if the answer code was as simple as possible to understand, as I am somewhat new to python. </p> <p>Any help with this error would be appreciated. Thanks!</p>
0
2016-10-07T23:26:12Z
39,927,143
<p>Download something like <a href="https://www.sublimetext.com/" rel="nofollow">Sublime</a> and highlight the code. Spaces will be dots and tabs will be dashes.</p>
2
2016-10-07T23:36:54Z
[ "python", "compiler-errors", "indentation" ]
Need read some data from JSON
39,927,140
<p>I need to make a get (id, name, fraction id) for each deputy in this json </p> <pre><code>{ "id": "75785", "title": "(за основу)", "asozdUrl": null, "datetime": "2011-12-21T12:20:26+0400", "votes": [ { "deputy": { "id": "99111772", "name": "Абалаков Александр Николаевич", "faction": { "id": "72100004", "title": "КПРФ" } }, "result": "accept" }, { "deputy": { "id": "99100491", "name": "Абдулатипов Рамазан Гаджимурадович", "faction": { "id": "72100024", "title": "ЕР" } }, "result": "none" } .......,` etc </code></pre> <hr> <p>My code is looks like that: </p> <pre><code>urlData = "https://raw.githubusercontent.com/data-dumaGovRu/vote/master/poll/2011-12-21/75785.json" response = urllib.request.urlopen(urlData) content = response.read() data = json.loads(content.decode("utf8")) for i in data: #print(data["name"]) </code></pre> <p>` And i dont know what to do with that #print line, how I should write it?</p>
-2
2016-10-07T23:36:28Z
39,927,172
<p>You can access the list containing the deputies with <code>data['votes']</code>. Iterating through the list, you can access the keys you're interested in as you would with dict key lookups. Nested dicts imply you have to walk through the keys starting from the root to your point of interest: </p> <pre><code>for d in data['votes']: print(d['deputy']['id'], d['deputy']['name'], d['deputy']['faction']['id']) </code></pre>
3
2016-10-07T23:41:13Z
[ "python", "json" ]
Convert pandas python data frame column values in place
39,927,141
<p>I have a column of positive and negative numbers and I want to convert it to a list of 0s and 1s. If the number if positive, it should be replaced with a 1. If the number is negative or 0, it should be replaced by a 0. How can I do this?</p> <p>For example, in R, I would do:</p> <pre><code>list = ifelse(list &gt; 0, 1, 0) </code></pre>
0
2016-10-07T23:36:34Z
39,927,166
<p>you can use an indexer and .loc to change values such has</p> <pre><code> indexer = df[df['col']&gt;0].index df.loc[indexer] = 1 indexer_2 = df[df['col']&lt;0].index df.loc[indexer_2] = 0 </code></pre> <p>or you can look at numpy.where such has</p> <pre><code>import numpy as np import pandas as pd pd.DataFrame(np.where(df&gt;0,1,0),index=df.index) </code></pre>
0
2016-10-07T23:40:18Z
[ "python", "pandas", "dataframe" ]
Convert pandas python data frame column values in place
39,927,141
<p>I have a column of positive and negative numbers and I want to convert it to a list of 0s and 1s. If the number if positive, it should be replaced with a 1. If the number is negative or 0, it should be replaced by a 0. How can I do this?</p> <p>For example, in R, I would do:</p> <pre><code>list = ifelse(list &gt; 0, 1, 0) </code></pre>
0
2016-10-07T23:36:34Z
39,927,177
<p>You can return <code>boolean</code> values and use <code>astype(int)</code> to convert them to <code>1</code> and <code>0</code>. </p> <pre><code>print((df['A'] &gt; 0).astype(int)) </code></pre> <p><strong>Example:</strong> </p> <pre><code>df = pd.DataFrame({'A': [1,-1,2,-2,3,-3]}) print(df) A 0 1 1 -1 2 2 3 -2 4 3 5 -3 print((df['A'] &gt; 0).astype(int)) 0 1 1 0 2 1 3 0 4 1 5 0 </code></pre>
1
2016-10-07T23:41:47Z
[ "python", "pandas", "dataframe" ]
Convert pandas python data frame column values in place
39,927,141
<p>I have a column of positive and negative numbers and I want to convert it to a list of 0s and 1s. If the number if positive, it should be replaced with a 1. If the number is negative or 0, it should be replaced by a 0. How can I do this?</p> <p>For example, in R, I would do:</p> <pre><code>list = ifelse(list &gt; 0, 1, 0) </code></pre>
0
2016-10-07T23:36:34Z
39,927,384
<p>You can use <code>DataFrame.apply</code> to apply a function to each row of your DataFrame. For instance:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'A': [1, -2, 3, -4]}) df['A'] = df.apply(lambda row:np.where(row['A'] &gt; 0, 1, 0), axis=1) </code></pre> <p>The <code>lambda</code> function can be replaced with any function (doesn't have to be a <code>lambda</code>), and <code>axis=1</code> is to apply the function to each row rather than each column.</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html</a></p>
0
2016-10-08T00:13:52Z
[ "python", "pandas", "dataframe" ]
Difference between Positional , keyword, optional and required argument?
39,927,162
<p>I am learning about functions in python and found many good tutorials and answers about functions and their types, but I am confused at some places. I have read the following:</p> <p>If function has <code>"="</code> then it's a keyword argument i.e <code>(a,b=2)</code> If function does not have <code>"="</code> then it's positional argument i.e <code>(a,b)</code></p> <p>My doubts :</p> <ul> <li><p>What is the meaning of a required argument and an optional argument ? Is default argument also a keyword argument? (since because both contain "=")</p></li> <li><p>Difference between the positional , keyword, optional and required arguments?</p></li> <li><p>python official documentation says that there are two types of arguments. If so, then what are <code>*args and **kargs</code> (I know how they work but don't know what they are)</p></li> <li><p>how <code>*args</code> and <code>**kargs</code> store values? I know how <code>*args</code> and <code>**kargs</code> works but how they store values? Does <code>*args</code> store values in tuple and <code>**kargs</code> in dictionary ?</p></li> </ul> <p>please explain in deep.I want to know about functions because I am a newbie :)</p> <p>Thanks in advance </p>
0
2016-10-07T23:39:39Z
39,927,217
<ul> <li>Optional arguments are those that have a default or those which are passed via *args and **kwargs. </li> <li>Any argument can be a keyword argument, it just depends on how it's called.</li> <li>these are used for passing variable numbers of args or keyword args</li> <li>yes and yes</li> </ul> <p>For more information see the tutorial:</p> <p><a href="https://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions" rel="nofollow">https://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions</a></p>
0
2016-10-07T23:47:04Z
[ "python", "python-2.7", "python-3.x" ]
Difference between Positional , keyword, optional and required argument?
39,927,162
<p>I am learning about functions in python and found many good tutorials and answers about functions and their types, but I am confused at some places. I have read the following:</p> <p>If function has <code>"="</code> then it's a keyword argument i.e <code>(a,b=2)</code> If function does not have <code>"="</code> then it's positional argument i.e <code>(a,b)</code></p> <p>My doubts :</p> <ul> <li><p>What is the meaning of a required argument and an optional argument ? Is default argument also a keyword argument? (since because both contain "=")</p></li> <li><p>Difference between the positional , keyword, optional and required arguments?</p></li> <li><p>python official documentation says that there are two types of arguments. If so, then what are <code>*args and **kargs</code> (I know how they work but don't know what they are)</p></li> <li><p>how <code>*args</code> and <code>**kargs</code> store values? I know how <code>*args</code> and <code>**kargs</code> works but how they store values? Does <code>*args</code> store values in tuple and <code>**kargs</code> in dictionary ?</p></li> </ul> <p>please explain in deep.I want to know about functions because I am a newbie :)</p> <p>Thanks in advance </p>
0
2016-10-07T23:39:39Z
39,927,275
<h2>Default Values</h2> <p>Let's imagine a function,</p> <pre><code>def function(a, b, c): print a print b print c </code></pre> <p>A positional argument is passed to the function in this way.</p> <pre><code>function("position1", "position2", "position3") </code></pre> <p>will print</p> <pre><code>position1 position2 position3 </code></pre> <p>However, you could pass in a keyword argument as below,</p> <pre><code>function(c="1",a="2",b="3") </code></pre> <p>and the output will become:</p> <pre><code>2 3 1 </code></pre> <p>The input is no longer based on the <strong>position</strong> of the argument, but now it is based on the <strong>keyword</strong>.</p> <p>The reason that <strong>b</strong> is optional in (a,b=2) is because you are giving it a default value. </p> <p>This means that if you only supply the function with one argument, it will be applied to <strong>a</strong>. A default value must be set in the function definition. This way when you omit the argument from the function call, the default will be applied to that variable. In this way it becomes 'optional' to pass in that variable.</p> <p>For example:</p> <pre><code>def function(a, b=10, c=5): print a print b print c function(1) </code></pre> <p>and the output will become:</p> <pre><code>1 10 5 </code></pre> <p>This is because you didn't give an argument for <strong>b</strong> or <strong>c</strong> so they used the default values. In this sense, <strong>b</strong> and <strong>c</strong> are optional because the function will not fail if you do not explicitly give them.</p> <h2>Variable length argument lists</h2> <p>The difference between *args and **kwargs is that a function like this:</p> <pre><code>def function(*args) for argument in args: print argument </code></pre> <p>can be called like this:</p> <pre><code>function(1,2,3,4,5,6,7,8) </code></pre> <p>and all of these arguments will be stored in a tuple called <strong>args</strong>. Keep in mind the variable name args can be replaced by any variable name, the required piece is the asterisk. </p> <p>Whereas,</p> <pre><code>def function(**args): keys = args.keys() for key in keys: if(key == 'somethingelse'): print args[key] </code></pre> <p>expects to be called like this:</p> <pre><code>function(key1=1,key2=2,key3=3,somethingelse=4,doesnt=5,matter=6) </code></pre> <p>and all of these arguments will be stored in a dict called <strong>args</strong>. Keep in mind the variable name args can be replaced by any variable name, the required piece is the double asterisk. </p> <p>In this way you will need to get the keys in some way:</p> <pre><code>keys = args.keys() </code></pre>
1
2016-10-07T23:55:39Z
[ "python", "python-2.7", "python-3.x" ]
Alternative for the DYLD_LIBRARY_PATH-trick since Mac OS 10.11 El Capitan with System Integrity Protection
39,927,235
<p><strong>Here is what I have:</strong></p> <ul> <li>Mac OS 10.11 El Capitan</li> <li>python 2.7.12, installed from python.org under <code>/Library/Frameworks/Python.framework/</code></li> <li>PyCharm 2016.2.3</li> <li>vtk 7.1.0</li> </ul> <p><strong>Here is what I do:</strong></p> <ul> <li><p>Build a python module locally. In my case, this is <a href="http://www.vtk.org/" rel="nofollow">vtk</a>. For a summary, see the CMake call with which I configure vtk. </p> <pre><code>cmake -G Ninja .. -DCMAKE_BUILD_TYPE=Release -DVTK_WRAP_PYTHON=ON -DBUILD_EXAMPLES=OFF -DBUILD_SHARED_LIBS=ON -DBUILD_TESTING=OFF -DCMAKE_INSTALL_PREFIX="/opt/dev/versions/vtk/vtk-7.1.0-shared" -DPYTHON_INCLUDE_DIR="/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/" -DPYTHON_LIBRARY="/Library/Frameworks/Python.framework/Versions/2.7/lib/libpython2.7.dylib" </code></pre></li> <li><p>Install the python package in a location where python can find it. In my case, this is <code>/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages</code> Note that I am required to extend the <code>DYLD_LIBRARY_PATH</code> by the location where the libs reside: <code>/opt/dev/versions/vtk/vtk-7.1.0-shared/lib/</code>. </p></li> <li><p>If I start python from the terminal, I can import vtk successfully.</p> <pre><code>import vtk v = vtk.vtkVersion() print v.GetVTKVersion() </code></pre></li> <li><p>If I try to import vtk in PyCharm's python console, I get the following error:</p> <pre><code>Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-2-b7e11aadda62&gt;", line 1, in &lt;module&gt; import vtk File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vtk/__init__.py", line 41, in &lt;module&gt; from .vtkCommonCore import * File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vtk/vtkCommonCore.py", line 9, in &lt;module&gt; from vtkCommonCorePython import * File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) ImportError: No module named vtkCommonCorePython </code></pre></li> </ul> <p>By now, I understand that the problem is caused by the <a href="https://en.wikipedia.org/wiki/System_Integrity_Protection" rel="nofollow">System Integrity Protection</a> (SIP) that has been introduced in El Capitan. One of the effects is that child processes only have <a href="https://developer.apple.com/library/content/documentation/Security/Conceptual/System_Integrity_Protection_Guide/RuntimeProtections/RuntimeProtections.html" rel="nofollow">restricted access</a> to other resources, and most likely, PyCharm executes python as separate process.</p> <p>I also understand that python cannot import vtk because it cannot find the dylibs which the python module links to. I can verify this in two ways:</p> <ul> <li>The <code>DYLD_LIBRARY_PATH</code> is empty. This is because python runs as a child process in PyCharm: <code>os.getenv('DYLD_LIBRARY_PATH')</code> returns <code>None</code>.</li> <li>When I copy all the libraries from <code>/opt/dev/versions/vtk/vtk-7.1.0-shared/lib/</code> to the current working directory, I can import the module</li> </ul> <p><strong>Now the question</strong>: Apparently, <code>DYLD_LIBRARY_PATH</code> cannot be used in child-processes and hence should not be used anymore at all since El Capitan. So, how to properly replace this "linkage hack" that worked perfectly well before MacOS 10.11.? Is there a way to still use <code>DYLD_LIBRARY_PATH</code>? </p> <p>Disabling SIP is not an option. Apparently, it helps to copy the dylibs into the current working directory, but this is not feasible for me. Placing the libs in the site-package location (of vtk) doesn't help however.</p> <p>I'm pretty sure that many people have been relying on the <code>DYLD_LIBRARY_PATH</code>-hack and now struggle with the consequences of SIP - that's why I thought that the community might benefit from this quite lengthy question.</p>
0
2016-10-07T23:50:11Z
39,967,241
<p>After a long struggle, I was able to solve the last bit of my problem.</p> <p>By setting a <strong>fixed value for the RPATH <a href="https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/RunpathDependentLibraries.html" rel="nofollow">Run-Path dependent Libraries</a> of the installed binaries</strong>, my linking problems are gone. </p> <p>There are different possibilities to achieve this. I guess one option is to use <code>install_name_tool</code>. For me, the easiest was to build vtk with appropriate CMake flags. Here my updated call to <code>cmake</code>, where <code>CMAKE_MACOSX_RPATH</code> and <code>CMAKE_INSTALL_RPATH</code> make the difference:</p> <pre><code> cmake -G Ninja .. -DCMAKE_BUILD_TYPE=Release \ -DVTK_WRAP_PYTHON=ON \ -DBUILD_EXAMPLES=OFF \ -DBUILD_SHARED_LIBS=ON \ -DBUILD_TESTING=OFF \ -DCMAKE_INSTALL_PREFIX="/opt/dev/versions/vtk/vtk-7.1.0-shared" \ -DCMAKE_MACOSX_RPATH=ON \ -DCMAKE_INSTALL_RPATH="/opt/dev/versions/vtk/vtk-7.1.0-shared/lib" \ -DPYTHON_INCLUDE_DIR="/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/" \ -DPYTHON_LIBRARY="/Library/Frameworks/Python.framework/Versions/2.7/lib/libpython2.7.dylib" </code></pre> <p>Read <a href="https://cmake.org/Wiki/CMake_RPATH_handling#Always_full_RPATH" rel="nofollow">here</a> more about CMake's rpath handling. Note that <code>otool -L vtkCommonCorePython.so</code> (for an example) will still write <code>@rpath</code> in the output, but the value still is fixed.</p> <pre><code>@rpath/libvtkCommonCorePython27D-7.1.1.dylib (compatibility version 0.0.0, current version 0.0.0) @rpath/libvtkWrappingPython27Core-7.1.1.dylib (compatibility version 0.0.0, current version 0.0.0) /Library/Frameworks/Python.framework/Versions/2.7/Python (compatibility version 2.7.0, current version 2.7.0) @rpath/libvtksys-7.1.1.dylib (compatibility version 0.0.0, current version 0.0.0) @rpath/libvtkCommonCore-7.1.1.dylib (compatibility version 0.0.0, current version 0.0.0) /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.1.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1226.10.1) </code></pre>
0
2016-10-10T21:46:13Z
[ "python", "osx", "vtk", "dyld" ]
How to do iterations to change dummy variable in multiple columns from 1 to 0 in Python and Pandas?
39,927,240
<p>I have a dataframe that have over 200 columns of dummy variable:</p> <pre><code>Row1 Feature1 Feature2 Feature3 Feature4 Feature5 A 0 1 1 1 0 B 0 0 1 1 1 C 1 0 1 0 1 D 0 1 0 1 0 </code></pre> <p>I want to do iteration to separate each feature to create extra 3 dataframes with df1 only contains keep the first feature that=1 as 1 and change all the later columns to 0 and df2 only contains keep the second feature that=1 as 1 and change all the previous and later columns to 0.</p> <p>I have create codes to do it, but I figured there gotta be better ways to do it. Please help me with a more efficient way to approach this. Thank you!</p> <p>Below is my code:</p> <pre><code>for index, row in hcit1.iterrows(): for i in range(1,261): title="feature"+str(i) if int(row[title])==1: for j in range(i+1,261): title2="feature"+str(j) hcit1.loc[index,title2]=0 else: pass for index, row in hcit2.iterrows(): for i in range(1,261): title="feature"+str(i) if int(row[title])==1: for j in range(i+1,261): title2="feature"+str(j) if row[title2]==1: for k in range(j+1,261): title3="feature"+str(k) hcit1.loc[index,title3]=0 hcit1.loc[index,title]=0 else: pass for index, row in hcit3.iterrows(): for i in range(1,261): title="feature"+str(i) if int(row[title])==1: for j in range(i+1,261): title2="feature"+str(j) if row[title2]==1: for k in range(j+1,261): title3="feature"+str(k) if row[title3]==1: for l in range(k+1,261): title4="feature"+str(l) hcit1.loc[index,title4]=0 hcit1.loc[index,title2]=0 hcit1.loc[index,title]=0 else: pass for index, row in hcit4.iterrows(): for i in range(1,261): title="feature"+str(i) if int(row[title])==1: for j in range(i+1,261): title2="feature"+str(j) if row[title2]==1: for k in range(j+1,261): title3="feature"+str(k) if row[title3]==1: for l in range(k+1,261): title4="feature"+str(l) if row[title4]==1: for m in range(l+1,261): title5="feature"+str(m) hcit1.loc[index,title5]=0 hcit1.loc[index,title3]=0 hcit1.loc[index,title2]=0 hcit1.loc[index,title]=0 else: pass </code></pre>
-2
2016-10-07T23:50:38Z
39,927,680
<p>Here:</p> <pre><code>df1 = df[df['Feature1'] == 1] df1.iloc[:, :] = 0 df1.loc[:, 'Feature1'] = 1 df2 = df[df['Feature2'] == 1] df2.iloc[:, :] = 0 df2.loc[:, 'Feature2'] = 1 df3 = df[df['Feature2'] == 1] df3.iloc[:, :] = 0 df3.loc[:, 'Feature3'] = 1 </code></pre> <p>That should be what you are looking for.</p>
0
2016-10-08T01:08:46Z
[ "python", "pandas", "for-loop" ]
Nested conditional transformation
39,927,244
<p>I am trying to write a small parser that converts nested conditional statements into one-liners conditionals. A basic example would be:</p> <pre><code>if age &gt; 15: if size == 3: test = 1 if size == 4: test = 2 </code></pre> <p><strong>translates to:</strong></p> <pre><code>'if age &gt; 15 and size == 3: test=1' 'if age &gt; 15 and size == 4: test=2' </code></pre> <p>I first tried using the python <code>ast</code> module but traversing a tree is probable not a good idea in this case. I am thinking that it's perhaps a good idea to use regular expressions. I am trying to get some help about a strategy to solve this problem.</p>
2
2016-10-07T23:51:20Z
39,927,730
<p>Try using a stack: (This program doesn't do any error checking, it assumes you code in the same way you did above, and tabs must be used, not 4 spaces)</p> <pre><code>mystack=[] toprint=[] ins=input('Next line: ') while ins!='': level=0 while ins[0]=='\t': ins=ins[1:] level+=1 if ins[0:2]=='if': if len(mystack)==level: mystack.append(ins[3:-1]) else: mystack=mystack[:level] mystack.append(ins[3:-1]) else: if level!=len(mystack): mystack=mystack[:level] toprint.append('if ') for i in mystack: toprint[-1]+=i toprint[-1]+=' and ' toprint[-1]=toprint[-1][:-5]+': ' toprint[-1]+=ins ins=input('Next line: ') print() for i in toprint: print(i) </code></pre>
1
2016-10-08T01:17:41Z
[ "python" ]
Creating a dictionary where the key is an integer and the value is the length of a random sentence
39,927,318
<p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p> <p>So far I'm able to create a dictionary where the values are the total number of each word but not the actual words themselves.</p> <p>So passing the following text</p> <pre><code>"the faith that he had had had had an affect on his life" </code></pre> <p>to the function</p> <pre><code>def get_word_len_dict(text): result_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6' :0} for word in text.split(): if str(len(word)) in result_dict: result_dict[str(len(word))] += 1 return result_dict </code></pre> <p>returns</p> <pre class="lang-none prettyprint-override"><code>1 - 0 2 - 3 3 - 6 4 - 2 5 - 1 6 - 1 </code></pre> <p>Where I need the output to be:</p> <pre class="lang-none prettyprint-override"><code>2 - ['an', 'he', 'on'] 3 - ['had', 'his', 'the'] 4 - ['life', 'that'] 5 - ['faith'] 6 - ['affect'] </code></pre> <p>I think I need to have to return the values as a list. But I'm not sure how to approach it.</p>
3
2016-10-08T00:02:11Z
39,927,339
<p>I think that what you want is a dic of lists.</p> <pre><code>result_dict = {'1':[], '2':[], '3':[], '4':[], '5':[], '6' :[]} for word in text.split(): if str(len(word)) in result_dict: result_dict[str(len(word))].append(word) return result_dict </code></pre>
1
2016-10-08T00:06:21Z
[ "python", "list", "python-3.x", "dictionary" ]
Creating a dictionary where the key is an integer and the value is the length of a random sentence
39,927,318
<p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p> <p>So far I'm able to create a dictionary where the values are the total number of each word but not the actual words themselves.</p> <p>So passing the following text</p> <pre><code>"the faith that he had had had had an affect on his life" </code></pre> <p>to the function</p> <pre><code>def get_word_len_dict(text): result_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6' :0} for word in text.split(): if str(len(word)) in result_dict: result_dict[str(len(word))] += 1 return result_dict </code></pre> <p>returns</p> <pre class="lang-none prettyprint-override"><code>1 - 0 2 - 3 3 - 6 4 - 2 5 - 1 6 - 1 </code></pre> <p>Where I need the output to be:</p> <pre class="lang-none prettyprint-override"><code>2 - ['an', 'he', 'on'] 3 - ['had', 'his', 'the'] 4 - ['life', 'that'] 5 - ['faith'] 6 - ['affect'] </code></pre> <p>I think I need to have to return the values as a list. But I'm not sure how to approach it.</p>
3
2016-10-08T00:02:11Z
39,927,356
<p>Instead of defining the default value as <code>0</code>, assign it as <code>set()</code> and within <code>if</code> condition do, <code>result_dict[str(len(word))].add(word)</code>. </p> <p><em>Also, instead of preassigning <code>result_dict</code>, you should use <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a>.</em> </p> <p><em>Since you need non-repetitive words, I am using <a href="https://docs.python.org/2/library/functions.html#func-set" rel="nofollow"><code>set</code></a> as value instead of <code>list</code>.</em> </p> <p>Hence, your final code should be:</p> <pre><code>from collections import defaultdict def get_word_len_dict(text): result_dict = defaultdict(set) for word in text.split(): result_dict[str(len(word))].add(word) return result_dict </code></pre> <p>In case it is must that you want <code>list</code> as values (I think <code>set</code> should suffice your requirement), you need to further iterate it as:</p> <pre><code>for key, value in result_dict.items(): result_dict[key] = list(value) </code></pre>
1
2016-10-08T00:08:44Z
[ "python", "list", "python-3.x", "dictionary" ]
Creating a dictionary where the key is an integer and the value is the length of a random sentence
39,927,318
<p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p> <p>So far I'm able to create a dictionary where the values are the total number of each word but not the actual words themselves.</p> <p>So passing the following text</p> <pre><code>"the faith that he had had had had an affect on his life" </code></pre> <p>to the function</p> <pre><code>def get_word_len_dict(text): result_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6' :0} for word in text.split(): if str(len(word)) in result_dict: result_dict[str(len(word))] += 1 return result_dict </code></pre> <p>returns</p> <pre class="lang-none prettyprint-override"><code>1 - 0 2 - 3 3 - 6 4 - 2 5 - 1 6 - 1 </code></pre> <p>Where I need the output to be:</p> <pre class="lang-none prettyprint-override"><code>2 - ['an', 'he', 'on'] 3 - ['had', 'his', 'the'] 4 - ['life', 'that'] 5 - ['faith'] 6 - ['affect'] </code></pre> <p>I think I need to have to return the values as a list. But I'm not sure how to approach it.</p>
3
2016-10-08T00:02:11Z
39,927,365
<p>the problem here is you are <em>counting</em> the word by length, instead you want to <em>group</em> them. You can achieve this by storing a list instead of a int:</p> <pre><code>def get_word_len_dict(text): result_dict = {} for word in text.split(): if len(word) in result_dict: result_dict[len(word)].add(word) else: result_dict[len(word)] = {word} #using a set instead of list to avoid duplicates return result_dict </code></pre> <p>Other improvements:</p> <ul> <li>don't hardcode the key in the initialized <code>dict</code> but let it empty instead. Let the code add the new keys dynamically when necessary</li> <li>you can use <code>int</code> as keys instead of strings, it will save you the conversion</li> <li>use <code>set</code>s to avoid repetitions</li> </ul> <hr> <h2>Using <code>groupby</code></h2> <p>Well, I'll try to propose something different: you can group by length using <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>groupby</code></a> from the python standard library</p> <pre><code>import itertools def get_word_len_dict(text): # split and group by length (you get a list if tuple(key, list of values) groups = itertools.groupby(sorted(text.split(), key=lambda x: len(x)), lambda x: len(x)) # convert to a dictionary with sets return {l: set(words) for l, words in groups} </code></pre>
1
2016-10-08T00:10:05Z
[ "python", "list", "python-3.x", "dictionary" ]
Creating a dictionary where the key is an integer and the value is the length of a random sentence
39,927,318
<p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p> <p>So far I'm able to create a dictionary where the values are the total number of each word but not the actual words themselves.</p> <p>So passing the following text</p> <pre><code>"the faith that he had had had had an affect on his life" </code></pre> <p>to the function</p> <pre><code>def get_word_len_dict(text): result_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6' :0} for word in text.split(): if str(len(word)) in result_dict: result_dict[str(len(word))] += 1 return result_dict </code></pre> <p>returns</p> <pre class="lang-none prettyprint-override"><code>1 - 0 2 - 3 3 - 6 4 - 2 5 - 1 6 - 1 </code></pre> <p>Where I need the output to be:</p> <pre class="lang-none prettyprint-override"><code>2 - ['an', 'he', 'on'] 3 - ['had', 'his', 'the'] 4 - ['life', 'that'] 5 - ['faith'] 6 - ['affect'] </code></pre> <p>I think I need to have to return the values as a list. But I'm not sure how to approach it.</p>
3
2016-10-08T00:02:11Z
39,927,367
<p>You say you want the keys to be integers but then you convert them to strings before storing them as a key. There is no need to do this in Python; integers can be dictionary keys.</p> <p>Regarding your question, simply initialize the values of the keys to empty lists instead of the number 0. Then, in the loop, append the word to the list stored under the appropriate key (the length of the word), like this:</p> <pre><code>string = "the faith that he had had had had an affect on his life" def get_word_len_dict(text): result_dict = {i : [] for i in range(1, 7)} for word in text.split(): length = len(word) if length in result_dict: result_dict[length].append(word) return result_dict </code></pre> <p>This results in the following:</p> <pre><code>&gt;&gt;&gt; get_word_len_dict(string) {1: [], 2: ['he', 'an', 'on'], 3: ['the', 'had', 'had', 'had', 'had', 'his'], 4: ['that', 'life'], 5: ['faith'], 6: ['affect']} </code></pre> <p>If you, as you mentioned, wish to remove the duplicate words when collecting your input string, it seems elegant to use a set and convert to a list as a final processing step, if this is needed. Also note the use of <code>defaultdict</code> so you don't have to manually initialize the dictionary keys and values as a default value <code>set()</code> (i.e. the empty set) gets inserted for each key that we try to access but not others:</p> <pre><code>from collections import defaultdict string = "the faith that he had had had had an affect on his life" def get_word_len_dict(text): result_dict = defaultdict(set) for word in text.split(): length = len(word) result_dict[length].add(word) return {k : list(v) for k, v in result_dict.items()} </code></pre> <p>This gives the following output:</p> <pre><code>&gt;&gt;&gt; get_word_len_dict(string) {2: ['he', 'on', 'an'], 3: ['his', 'had', 'the'], 4: ['life', 'that'], 5: ['faith'], 6: ['affect']} </code></pre>
1
2016-10-08T00:10:10Z
[ "python", "list", "python-3.x", "dictionary" ]
Creating a dictionary where the key is an integer and the value is the length of a random sentence
39,927,318
<p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p> <p>So far I'm able to create a dictionary where the values are the total number of each word but not the actual words themselves.</p> <p>So passing the following text</p> <pre><code>"the faith that he had had had had an affect on his life" </code></pre> <p>to the function</p> <pre><code>def get_word_len_dict(text): result_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6' :0} for word in text.split(): if str(len(word)) in result_dict: result_dict[str(len(word))] += 1 return result_dict </code></pre> <p>returns</p> <pre class="lang-none prettyprint-override"><code>1 - 0 2 - 3 3 - 6 4 - 2 5 - 1 6 - 1 </code></pre> <p>Where I need the output to be:</p> <pre class="lang-none prettyprint-override"><code>2 - ['an', 'he', 'on'] 3 - ['had', 'his', 'the'] 4 - ['life', 'that'] 5 - ['faith'] 6 - ['affect'] </code></pre> <p>I think I need to have to return the values as a list. But I'm not sure how to approach it.</p>
3
2016-10-08T00:02:11Z
39,927,394
<p>Fixing Sabian's answer so that duplicates aren't added to the list:</p> <pre><code>def get_word_len_dict(text): result_dict = {1:[], 2:[], 3:[], 4:[], 5:[], 6 :[]} for word in text.split(): n = len(word) if n in result_dict and word not in result_dict[n]: result_dict[n].append(word) return result_dict </code></pre>
1
2016-10-08T00:15:36Z
[ "python", "list", "python-3.x", "dictionary" ]
Creating a dictionary where the key is an integer and the value is the length of a random sentence
39,927,318
<p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p> <p>So far I'm able to create a dictionary where the values are the total number of each word but not the actual words themselves.</p> <p>So passing the following text</p> <pre><code>"the faith that he had had had had an affect on his life" </code></pre> <p>to the function</p> <pre><code>def get_word_len_dict(text): result_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6' :0} for word in text.split(): if str(len(word)) in result_dict: result_dict[str(len(word))] += 1 return result_dict </code></pre> <p>returns</p> <pre class="lang-none prettyprint-override"><code>1 - 0 2 - 3 3 - 6 4 - 2 5 - 1 6 - 1 </code></pre> <p>Where I need the output to be:</p> <pre class="lang-none prettyprint-override"><code>2 - ['an', 'he', 'on'] 3 - ['had', 'his', 'the'] 4 - ['life', 'that'] 5 - ['faith'] 6 - ['affect'] </code></pre> <p>I think I need to have to return the values as a list. But I'm not sure how to approach it.</p>
3
2016-10-08T00:02:11Z
39,927,424
<p>Check out <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">list comprehensions</a></p> <p>Integers are legal dictionaries keys so there is no need to make the numbers strings unless you want it that way for some other reason. <code>if statement</code> in the <code>for loop</code> controls flow to add word only once. You could get this effect more automatically if you use <code>set()</code> type instead of <code>list()</code> as your value data structure. See more in the docs. I believe the following does the job:</p> <pre><code>def get_word_len_dict(text): result_dict = {len(word) : [] for word in text.split()} for word in text.split(): if word not in result_dict[len(word)]: result_dict[len(word)].append(word) return result_dict </code></pre> <p>try to make it better ;)</p>
1
2016-10-08T00:22:36Z
[ "python", "list", "python-3.x", "dictionary" ]
Creating a dictionary where the key is an integer and the value is the length of a random sentence
39,927,318
<p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p> <p>So far I'm able to create a dictionary where the values are the total number of each word but not the actual words themselves.</p> <p>So passing the following text</p> <pre><code>"the faith that he had had had had an affect on his life" </code></pre> <p>to the function</p> <pre><code>def get_word_len_dict(text): result_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6' :0} for word in text.split(): if str(len(word)) in result_dict: result_dict[str(len(word))] += 1 return result_dict </code></pre> <p>returns</p> <pre class="lang-none prettyprint-override"><code>1 - 0 2 - 3 3 - 6 4 - 2 5 - 1 6 - 1 </code></pre> <p>Where I need the output to be:</p> <pre class="lang-none prettyprint-override"><code>2 - ['an', 'he', 'on'] 3 - ['had', 'his', 'the'] 4 - ['life', 'that'] 5 - ['faith'] 6 - ['affect'] </code></pre> <p>I think I need to have to return the values as a list. But I'm not sure how to approach it.</p>
3
2016-10-08T00:02:11Z
39,927,438
<p>What you need is a map to list-construct (if not many words, otherwise a 'Counter' would be fine): Each list stands for a word class (number of characters). Map is checked whether word class ('3') found before. List is checked whether word ('had') found before.</p> <pre><code>def get_word_len_dict(text): result_dict = {} for word in text.split(): if not result_dict.get(str(len(word))): # add list to map? result_dict[str(len(word))] = [] if not word in result_dict[str(len(word))]: # add word to list? result_dict[str(len(word))].append(word) return result_dict </code></pre> <p>--></p> <pre><code>3 ['the', 'had', 'his'] 2 ['he', 'an', 'on'] 5 ['faith'] 4 ['that', 'life'] 6 ['affect'] </code></pre>
1
2016-10-08T00:24:30Z
[ "python", "list", "python-3.x", "dictionary" ]
Creating a dictionary where the key is an integer and the value is the length of a random sentence
39,927,318
<p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p> <p>So far I'm able to create a dictionary where the values are the total number of each word but not the actual words themselves.</p> <p>So passing the following text</p> <pre><code>"the faith that he had had had had an affect on his life" </code></pre> <p>to the function</p> <pre><code>def get_word_len_dict(text): result_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6' :0} for word in text.split(): if str(len(word)) in result_dict: result_dict[str(len(word))] += 1 return result_dict </code></pre> <p>returns</p> <pre class="lang-none prettyprint-override"><code>1 - 0 2 - 3 3 - 6 4 - 2 5 - 1 6 - 1 </code></pre> <p>Where I need the output to be:</p> <pre class="lang-none prettyprint-override"><code>2 - ['an', 'he', 'on'] 3 - ['had', 'his', 'the'] 4 - ['life', 'that'] 5 - ['faith'] 6 - ['affect'] </code></pre> <p>I think I need to have to return the values as a list. But I'm not sure how to approach it.</p>
3
2016-10-08T00:02:11Z
39,927,669
<p>Your code is counting the occurrence of each word length - but not storing the words themselves.</p> <p>In addition to capturing each word into a list of words with the same size, you also appear to want:</p> <ol> <li>If a word length is not represented, do not return an empty list for that length - just don't have a key for that length.</li> <li>No duplicates in each word list</li> <li>Each word list is sorted</li> </ol> <p>A set container is ideal for accumulating the words - sets naturally eliminate any duplicates added to them. </p> <p>Using defaultdict(sets) will setup an empty dictionary of sets -- a dictionary key will only be created if it is referenced in our loop that examines each word.</p> <pre><code>from collections import defaultdict def get_word_len_dict(text): #create empty dictionary of sets d = defaultdict(set) # the key is the length of each word # The value is a growing set of words # sets automatically eliminate duplicates for word in text.split(): d[len(word)].add(word) # the sets in the dictionary are unordered # so sort them into a new dictionary, which is returned # as a dictionary of lists return {i:sorted(d[i]) for i in d.keys()} </code></pre> <p>In your example string of </p> <pre><code>a="the faith that he had had had had an affect on his life" </code></pre> <p>Calling the function like this:</p> <pre><code>z=get_word_len_dict(a) </code></pre> <p>Returns the following list:</p> <pre><code>print(z) {2: ['an', 'he', 'on'], 3: ['had', 'his', 'the'], 4: ['life', 'that'], 5: ['faith'], 6: ['affect']} </code></pre> <p>The type of each value in the dictionary is "list".</p> <pre><code>print(type(z[2])) &lt;class 'list'&gt; </code></pre>
1
2016-10-08T01:07:22Z
[ "python", "list", "python-3.x", "dictionary" ]
With matplotlib, how can I create a 2D histogram with polar projection and a symlog r-axis?
39,927,348
<p>I have been having trouble creating polar histograms with symlog axis. However this only breaks when there are negative r-values. What can I do to fix this?</p> <p>I've included a minimal example which displays 5 plots. Plot 4 is the one which does not work (middle row right.) Plot 5 is to show it working with positive numbers. </p> <p>Here's the output:</p> <p><a href="http://i.stack.imgur.com/We4MX.png" rel="nofollow"><img src="http://i.stack.imgur.com/We4MX.png" alt="enter image description here"></a> </p> <p>Here's the code: </p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.scale import SymmetricalLogTransform MIN_BINS = 500 MAX_BINS = 1000 # utility function for making bins of correct size def get_bins(min_val, max_val, scaling): w = 1 + max(MIN_BINS, min(MAX_BINS, abs(min_val - max_val) + 1)) if scaling == 'log': return np.logspace(np.log10(min_val), np.log10(max_val), w) elif scaling == 'symlog': tr = SymmetricalLogTransform(base=10, linthresh=1, linscale=1) ss = tr.transform([min_val, max_val]) ls = tr.inverted().transform(np.linspace(*ss, num=w)) return ls else:# linear return np.linspace(min_val, max_val, w) TESTS = [1,2,3,4,5] plt.figure(figsize=(12,18)) plot_pos = 320 for TEST in TESTS: plot_pos += 1 if TEST == 1: NEG = True YSCALE = 'linear' PROJECTION = None if TEST == 2: NEG = True YSCALE = 'symlog' PROJECTION = None if TEST == 3: NEG = True YSCALE = 'linear' PROJECTION = 'polar' # This is what I want to work if TEST == 4: NEG = True YSCALE = 'symlog' PROJECTION = 'polar' # However, remove the negative numbers and it seems to work if TEST == 5: NEG = False YSCALE = 'symlog' PROJECTION = 'polar' sample_size = 100000 xs = np.pi * np.linspace(0.0, 2.0, sample_size) ys = 20 * np.random.random(sample_size) if NEG: ys -= 10 ax = plt.subplot(plot_pos, projection=PROJECTION) ax.set_title('Neg/Scale/Proj.:%s,%s,%s' % (NEG, YSCALE, PROJECTION)) min_y = np.min(ys) max_y = np.max(ys) min_x = np.min(xs) max_x = np.max(xs) x_bins = get_bins(min_x, max_x, 'linear') y_bins = get_bins(min_y, max_y, YSCALE) hist, xedges, yedges = np.histogram2d( xs, ys, bins=[x_bins, y_bins] ) X, Y = np.meshgrid(xedges, yedges) ax.pcolormesh( X, Y, hist.T, cmap=cm.gray_r, ) if PROJECTION == 'polar': ax.set_rscale(YSCALE) ax.set_rmax(max_y) ax.set_rmin(min_y) else: ax.set_ylim([min_y, max_y]) ax.set_yscale(YSCALE) ax.grid(True) plt.savefig('polar_example.png') </code></pre>
1
2016-10-08T00:07:02Z
39,927,516
<p>This might be a bug in matplotlib, unfortunately polar plots have multiple <a href="https://github.com/matplotlib/matplotlib/issues/7130" rel="nofollow">scaling issues</a> and <a href="https://github.com/matplotlib/matplotlib/issues/7120#issuecomment-247460462" rel="nofollow">might have to go through some major revisions in the future</a>.</p> <p>I suspect that the issue is this, for your problematic fourth <code>polar</code>-<code>symlog</code> axes:</p> <pre><code>&gt;&gt;&gt; ax.get_rmin() -9.9998049982336408 &gt;&gt;&gt; ax.get_rmax() 9.9999564676741315 </code></pre> <p>Negative radii are present since <code>symlog</code> is prepared to handle them. However, matplotlib had some issues plotting these values, and <a href="https://github.com/matplotlib/matplotlib/pull/4699" rel="nofollow">corresponding behaviour even changed in the past</a>. I think the only problem now is that the negative radial limits passed in during the call to <code>ax.set_rmin()</code> are interpreted as reflected positive values. Here's your test when I change the radial case to</p> <pre><code>if PROJECTION == 'polar': ax.set_rscale(YSCALE) ax.set_rmax(max_y) ax.set_rmin(max(0,min_y)) # change here </code></pre> <p><a href="http://i.stack.imgur.com/u9eXR.png" rel="nofollow"><img src="http://i.stack.imgur.com/u9eXR.png" alt="fixed result"></a></p>
1
2016-10-08T00:39:17Z
[ "python", "matplotlib", "plot", "polar-coordinates" ]
MultiProcessing Lock() doesn't work
39,927,405
<p>I have a program that reads some input text files and write all of them into a list called <code>ListOutput</code> which is a shared memory between two processes used in my program (I used two processes so my program runs faster!) I also have a shared memory variable called <code>processedFiles</code> which stores the names of the already read input files by any of the processes so the current process does not read them again!</p> <ol> <li><p>To make sure that two processes do not check the "processedFiles" at the same time (For example in the beginning, it is possible that at the same time they both may come to the conclusion that "processedFiles" is empty so they read the same file), therefore, I added a <code>Lock</code> around the checking part for <code>processedFiles</code> so one process should complete and release the locked part before the other process checking in to that part!</p> <p>My problem is that the <code>Lock</code> function seems not to work and when I print the current <code>ProcessName</code> inside the lock part, it shows that both processes are inside the lock part. I cannot figure out what is wrong with my code? (See the output below.)</p></li> <li><p>Since my main program is not only about reading the input text files and printing them in the list, but it has to do a very complicate operation on the input files before printing them into a list, should I use <code>Pool</code> instead of <code>Process</code> and why?</p></li> </ol> <p>Code:</p> <pre><code>import glob from multiprocessing import Process, Manager from threading import * import timeit import os os.chdir("files") def print_content(ProcessName,processedFiles,ListOutput,lock): for file in glob.glob("*.txt"): newfile=0 lock.acquire() print "\n Current Process:",ProcessName if file not in processedFiles: print "\n", file, " not in ", processedFiles," for ",ProcessName processedFiles.append(file) newfile=1#it is a new file lock.release() #if it is a new file if newfile==1: f = open(file,"r") lines = f.readlines() ListOutput.append(lines) f.close() # Create two processes as follows try: manager = Manager() processedFiles = manager.list() ListOutput = manager.list() lock=Lock() p1 = Process(target=print_content, args=("Procees-1",processedFiles,ListOutput,lock)) p2 = Process(target=print_content, args=("Process-2",processedFiles,ListOutput,lock)) p1.start() p2.start() p1.join() p2.join() print "ListOutput",ListOutput except: print "Error: unable to start process" </code></pre> <p>I have 4 input files called <code>1.txt</code> (contains "my car"), <code>2.txt</code> (contains "your car"), <code>3.txt</code> (contains "my book"), <code>4.txt</code> (contains "your book"). The output that it shows me changes in different runs. This is the output in one of the runs:</p> <pre class="lang-none prettyprint-override"><code>Current Process: Procees-1 Current Process: Process-2 1.txt not in [] for Procees-1 Current Process: Procees-1 2.txt not in Current Process: Process-2 ['1.txt'] for Procees-1 2.txt not in ['1.txt', '2.txt'] for Process-2 Current Process: Procees-1 3.txt not in ['1.txt', '2.txt', '2.txt'] for Procees-1 Current Process: Process-2 Current Process: Process-2 4.txt not in Current Process: Procees-1 ['1.txt', '2.txt', '2.txt', '3.txt'] for Process-2 4.txt not in ['1.txt', '2.txt', '2.txt', '3.txt', '4.txt'] for Procees-1 ListOutput [['my car'], ['your car'], ['your car'], ['my book'], ['your book'], ['your book']] </code></pre>
0
2016-10-08T00:17:54Z
39,927,566
<p>Bingo! Thanks for including the imports. <em>Now</em> the problem is obvious ;-)</p> <p>You need to use a <code>multiprocessing.Lock</code> to get a lock that works across processes. The <code>Lock</code> you're actually using is implicitly obtained along with a mountain of other stuff via your</p> <pre><code>from threading import * </code></pre> <p>A <code>threading.Lock</code> is useless for your purpose: it has no effect whatsoever <em>across</em> processes; it only provides exclusion among threads <em>within</em> a single process.</p> <p>It's usually a Bad Idea to use <code>import *</code>, and this is one reason why. Even if you changed your second import to</p> <pre><code>from multiprocessing import Process, Manager, Lock ^^^^ </code></pre> <p>it wouldn't do you any good, because <code>from threading import *</code> would overwrite the <code>Lock</code> you really want.</p>
1
2016-10-08T00:48:04Z
[ "python", "multithreading", "multiprocessing" ]
Forcing Unload/Deconstruction of Dynamically Imported File from Source
39,927,422
<p>Been a longtime browser of SO, finally asking my own questions!</p> <p>So, I am writing an automation script/module that looks through a directory recursively for python modules with a specific name. If I find a module with that name, I load it dynamically, pull what I need from it, and then unload it. I noticed though that simply del'ing the module does not remove all references to that module, there is another lingering somewhere and I do not know where it is. I tried taking a peek at the source code, but couldn't make sense of it too well. Here is a sample of what I am seeing, greatly simplified:</p> <p>I am using Python 3.5.2 (Anaconda v4.2.0). I am using importlib, and that is what I want to stick with. I also want to be able to do this with vanilla python-3. </p> <p>I got the import from source from the python docs <a href="https://docs.python.org/3.6/library/importlib.html#importing-a-source-file-directly%22here%22" rel="nofollow">here</a> (yes I am aware this is the Python 3.6 docs).</p> <p>My main driver...</p> <pre><code># main.py import importlib.util import sys def foo(): spec = importlib.util.spec_from_file_location('a', 'a.py') module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) print(sys.getrefcount(module)) del module del spec if __name__ == '__main__': foo() print('THE END') </code></pre> <p>And my sample module...</p> <pre><code># a.py print('hello from a') class A(): def __del__(self): print('SO LONG A!') inst = A() </code></pre> <p>Output:</p> <pre><code>python main.py HELLO FROM A! 2 THE END SO LONG A! </code></pre> <p>I expected to see "SO LONG A!" printed before "THE END". So, where is this other hidden reference to my module? I understand that my del's are gratuitous with the fact that I have it wrapped in a function. I just wanted the deletion and scope to be explicit. How do I get a.py to completely unload? I plan on dynamically loading a ton of modules like a.py, and I do not want to hold on to them any longer than I really have to. Is there something I am missing?</p>
0
2016-10-08T00:22:08Z
39,927,557
<p>There is a <em>circular reference</em> here, the module object references objects that reference the module again.</p> <p>This means the module is not cleared immediately (as the reference count never goes to 0 by itself). You need to wait for the circle to be broken by the garbage collector.</p> <p>You can force this by calling <a href="https://docs.python.org/3/library/gc.html#gc.collect" rel="nofollow"><code>gc.collect()</code></a>:</p> <pre><code>import gc # ... if __name__ == '__main__': foo() gc.collect() print('THE END') </code></pre> <p>With that in place, the output becomes:</p> <pre><code>$ python main.py hello from a 2 SO LONG A! THE END </code></pre>
0
2016-10-08T00:46:12Z
[ "python", "python-3.x", "python-importlib" ]
Using forms with the Django outputs the token
39,927,463
<p>I would really appreciate if you can give a hand with this. What I'm trying to do it's just to render the value of some text label, but it gives me the token.</p> <p>I'm learning django I hope you can comprehend.</p> <p>The result of this is:</p> <p><strong>eee 12121 csrfmiddlewaretoken yYvl3neQZSP33vSRNto3FUFa88AMeFQi</strong></p> <p>view.</p> <pre><code>def test(request): if request.method == "POST": response = '' for key, value in request.POST.items(): response += '%s %s\n' % (key, value) return HttpResponse(response) return render(request, 'datos2.html') </code></pre> <p>datos2.</p> <pre><code>&lt;form action="/test" method="post"&gt; {% csrf_token %} &lt;input type="text" name="eee"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;p&gt;ADD VALUE&lt;/p&gt; &lt;button onclick="myFunction()"&gt;ADD&lt;/button&gt; &lt;script&gt; function myFunction() { var x = document.createElement("INPUT"); x.setAttribute("type", "text"); x.setAttribute("value", "0"); x.setAttribute("name", "eee"); document.body.appendChild(x); } &lt;/script&gt; </code></pre> <p><a href="http://i.stack.imgur.com/qx75Z.png" rel="nofollow"><img src="http://i.stack.imgur.com/qx75Z.png" alt="enter image description here"></a></p> <hr> <p><a href="http://i.stack.imgur.com/uqMv3.png" rel="nofollow"><img src="http://i.stack.imgur.com/uqMv3.png" alt="enter image description here"></a></p>
0
2016-10-08T00:29:22Z
39,927,570
<p>You are looping over all the elements in the POST array in this snippet of code</p> <pre><code>for key, value in request.POST.items(): response += '%s %s\n' % (key, value) </code></pre> <p>I believe, if i understand your question, that what you are after is simply <code>request.POST.get('eee')</code></p>
1
2016-10-08T00:48:33Z
[ "python", "django", "token", "csrf" ]
Pyevolve Score in Evaluation function
39,927,468
<p>Here is an example of pyevolve library of Python,</p> <pre><code>from pyevolve import G1DList from pyevolve import GSimpleGA import time def eval_func(chromosome): score = 0.0 for value in chromosome: if value == 50: score += 1 return score genome = G1DList.G1DList(20) genome.evaluator.set(eval_func) ga = GSimpleGA.GSimpleGA(genome) ga.evolve(freq_stats=10) print ga.bestIndividual() </code></pre> <p>In this example score makes sense as with every increment in score the output will get more accurate.</p> <p>But if I want sum of chromosome element to be some particular value say 200, then how to determine the score or what is the best way to create score. </p> <p>Thanks </p> <p>EDIT:</p> <p>Here is the code for sum, but its not giving the correct/desired output. It will always be either greater or less than the required answer. </p> <pre><code>from pyevolve import G1DList from pyevolve import GSimpleGA import time def eval_func(chromosome): score = 0.0 sum_ = 0.0 for value in chromosome: sum_ = sum_ + value score_ = abs(200 - sum_) score = float(1/score_) return score genome = G1DList.G1DList(20) genome.evaluator.set(eval_func) ga = GSimpleGA.GSimpleGA(genome) ga.evolve(freq_stats=10) print ga.bestIndividual() </code></pre> <p>Please suggest some better score evaluation method.</p>
0
2016-10-08T00:30:23Z
39,927,523
<p>Have the evaluation function take every element of the list and add the value of every element of the list. Then subtract the desired value from the the value you get and take the absolute value of the result. Finally put this under a a fraction like 1/(value) to return the highest value for the smallest number.</p>
0
2016-10-08T00:39:55Z
[ "python", "algorithm", "artificial-intelligence", "genetic-algorithm", "pyevolve" ]
using a while True loop
39,927,504
<p><strong>Problem 1.</strong></p> <p>This problem provides practice using a <code>while True</code> loop. Write a function named <code>twoWords</code> that gets and returns two words from a user. The first word is of a specified length, and the second word begins with a specified letter.</p> <p>The function <code>twoWords</code> takes two parameters:</p> <ol> <li>an integer, <code>length</code>, that is the length of the first word and</li> <li>a character, <code>firstLetter</code>, that is the first letter of the second word.</li> </ol> <p>The second word may begin with either an upper or lower case instance of <code>firstLetter</code>. The function <code>twoWords</code> should return the two words in a list. Use a <code>while True</code> loop and a <code>break</code> statement in the implementation of <code>twoWords</code>. The following is an example of the execution of <code>twoWords</code>: <code>print(twoWords(4, 'B'))</code>:</p> <pre><code>A 4-letter word please two A 4-letter word please one A 4-letter word please four A word beginning with B please apple A word beginning with B please pear A word beginning with B please banana ['four', 'banana'] </code></pre> <hr> <p>This is what I have so far, but it keeps asking me the first question over again even if I have the right word length. What am I doing wrong?</p> <pre><code>def twoWords(length, firstLetter): wordLen = input('A 4-letter word please ') while len(wordLen) != int(length): wordlen = input('A 4-letter word please ') word = input('A word beginning with ' + firstLetter + ' please ') while word[0] != firstLetter: word = input('A word beginning with ' + firstLetter + ' please ') return[wordLen, word] </code></pre>
-5
2016-10-08T00:37:17Z
39,951,286
<pre><code>def twoWords(length,firstLetter): firstWord = "" secondWord= "" while True: firstWord = input('A ' + str(length) + '-letter word please.') if length == len(firstWord): break while True: secondWord = input('A word beginning with ' + firstLetter+ ' please') if secondWord[0] == firstLetter.upper() or secondWord[0] == firstLetter.lower(): break return [firstWord,secondWord] print(twoWords(4,'B')) </code></pre>
0
2016-10-10T04:23:30Z
[ "python", "while-loop" ]
Django Project parsing parameters in request
39,927,529
<p>I have request to my django project from ExtJS application:</p> <pre><code>GET /products/?page=1&amp;start=0&amp;limit=25&amp;sort=%5B%7B%22property%22%3A%22id%22%2C%22direction%22%3A%22DESC%22%7D%5D </code></pre> <p>At the request contains 4 parameters, one of which is a complex, which is called <strong>sort</strong>:</p> <p><a href="http://i.stack.imgur.com/tVqIA.png" rel="nofollow"><img src="http://i.stack.imgur.com/tVqIA.png" alt="screen"></a></p> <p>Question: how to extract the values of the parameters <strong>property</strong> and <strong>direction</strong> using Python? </p> <p>I did so, but it does not work. I would be glad of any help.</p> <pre class="lang-python prettyprint-override"><code>class ProductsList(generics.ListCreateAPIView): serializer_class = ProductsSerializer def get_queryset(self): queryset = Products.objects.all() sortParameter = self.request.query_params.get('sort', None) column_name=sortParameter['property'] queryset = queryset.order_by(column_name) return queryset </code></pre> <p>If you know the best way to sort and filter the data on the server side for Django Rest projects, please share your ideas or references.</p>
0
2016-10-08T00:40:45Z
39,928,087
<p>There is probably more elegant solution, by I just intercept all ajax requests and convert <code>sort</code> parameter to DRF-friendly <code>ordering</code>:</p> <pre><code>Ext.Ajax.on('beforerequest', function (conn, options) { if(options.params &amp;&amp; options.params.sort) { var ordering = options.params.ordering ? options.params.ordering.split(',') : []; var sortArray = JSON.parse(options.params.sort); sortArray.forEach(function(el){ ordering.push((el.direction == 'DESC' ? '-' : '') + el.property); }); options.params.ordering = ordering.join(','); } }, this); </code></pre>
0
2016-10-08T02:27:18Z
[ "python", "django", "extjs", "django-rest-framework" ]
Django Project parsing parameters in request
39,927,529
<p>I have request to my django project from ExtJS application:</p> <pre><code>GET /products/?page=1&amp;start=0&amp;limit=25&amp;sort=%5B%7B%22property%22%3A%22id%22%2C%22direction%22%3A%22DESC%22%7D%5D </code></pre> <p>At the request contains 4 parameters, one of which is a complex, which is called <strong>sort</strong>:</p> <p><a href="http://i.stack.imgur.com/tVqIA.png" rel="nofollow"><img src="http://i.stack.imgur.com/tVqIA.png" alt="screen"></a></p> <p>Question: how to extract the values of the parameters <strong>property</strong> and <strong>direction</strong> using Python? </p> <p>I did so, but it does not work. I would be glad of any help.</p> <pre class="lang-python prettyprint-override"><code>class ProductsList(generics.ListCreateAPIView): serializer_class = ProductsSerializer def get_queryset(self): queryset = Products.objects.all() sortParameter = self.request.query_params.get('sort', None) column_name=sortParameter['property'] queryset = queryset.order_by(column_name) return queryset </code></pre> <p>If you know the best way to sort and filter the data on the server side for Django Rest projects, please share your ideas or references.</p>
0
2016-10-08T00:40:45Z
39,932,879
<p>I solved the problem by using json package. Thanks for the advice <strong><em>furas</em></strong></p> <pre><code>def get_queryset(self): queryset = Products.objects.all() sortParameter = self.request.query_params.get('sort', None) parsed_sort=json.loads(sortParameter) column_name=parsed_sort[0]['property'] queryset = queryset.order_by(column_name) return queryset </code></pre> <p>But I think the code is not optimal? What is the best practice: build url on backend side then send a request to the server and the server to do a minimum number of operations to retrieve the request parameters. Or parse request parameters on the server side.</p>
0
2016-10-08T13:22:55Z
[ "python", "django", "extjs", "django-rest-framework" ]
How to make django server public in rasb?
39,927,569
<p>I use django server. First, I do port forwarding my raspberrypi ( my public ip : 12345) using my Sharer.</p> <p>So, I can access my raspberrypi server using x-shell(putty) and then I want to access my dajngo web server. In my home I can access my django server (192.168.1.11:8000)</p> <p>But I can't access my django server except my home wifi-zone.</p> <p>I think i have to do port forwarding one more, but I'm not sure. Then, what can i do?</p> <p><a href="http://i.stack.imgur.com/qUlHk.png" rel="nofollow"><img src="http://i.stack.imgur.com/qUlHk.png" alt="Screenshot"></a></p>
0
2016-10-08T00:48:25Z
39,928,486
<p>Are you asking to host a webserver/django app from your home network, to the public internet?</p> <p>If so, I do not have the technical detail on how to accomplish that - but from a security perspective that is not a great idea. You might want to look into some of the free/cheap hosts out there that support python and django</p>
1
2016-10-08T03:49:44Z
[ "python", "django", "raspberry-pi" ]
memory error while performing matrix multiplication
39,927,586
<p>As part of a project I'm working on, I need to calculate the mean squared error between <code>2m</code> vectors.</p> <p>Basically I two matrices <code>x</code> and <code>xhat</code>, both are size <code>m</code> by <code>n</code> and the vectors I'm interested in are the rows of these vectors.</p> <p>I calculate the MSE with this code</p> <pre><code>def cost(x, xhat): #mean squared error between x the data and xhat the output of the machine return (1.0/(2 * m)) * np.trace(np.dot(x-xhat,(x-xhat).T)) </code></pre> <p>It's working correctly, this formula is correct.</p> <p>The problem is that in my specific case, my <code>m</code> and <code>n</code> are very large. specifically, <code>m = 60000</code> and <code>n = 785</code>. So when I run my code and it enters this function, I get a memory error.</p> <p>Is there a better way to calculate the MSE? I'd rather avoid for loops and I lean heavily towards matrix multiplication, but matrix multiplication seems extremely wasteful here. Maybe something in numpy I'm not aware of?</p>
1
2016-10-08T00:51:42Z
39,928,411
<p>The expression <code>np.dot(x-xhat,(x-xhat).T)</code> creates an array with shape (m, m). You say m is 60000, so that array is almost 29 gigabytes.</p> <p>You take the trace of the array, which is just the sum of the diagonal elements, so most of that huge array is unused. If you look carefully at <code>np.trace(np.dot(x-xhat,(x-xhat).T))</code>, you'll see that it is just the sum of the squares of all the elements of <code>x - xhat</code>. So a simpler way to compute <code>np.trace(np.dot(x-xhat,(x-xhat).T))</code> that doesn't require the huge intermediate array is <code>((x - xhat)**2).sum()</code>. For example,</p> <pre><code>In [44]: x Out[44]: array([[ 0.87167186, 0.96838389, 0.72545457], [ 0.05803253, 0.57355625, 0.12732163], [ 0.00874702, 0.01555692, 0.76742386], [ 0.4130838 , 0.89307633, 0.49532327], [ 0.15929044, 0.27025289, 0.75999848]]) In [45]: xhat Out[45]: array([[ 0.20825392, 0.63991699, 0.28896932], [ 0.67658621, 0.64919721, 0.31624655], [ 0.39460861, 0.33057769, 0.24542263], [ 0.10694332, 0.28030777, 0.53177585], [ 0.21066692, 0.53096774, 0.65551612]]) In [46]: np.trace(np.dot(x-xhat,(x-xhat).T)) Out[46]: 2.2352330441581061 In [47]: ((x - xhat)**2).sum() Out[47]: 2.2352330441581061 </code></pre> <p>For more ideas about computing the MSE, see the <a href="http://stackoverflow.com/questions/16774849/mean-squared-error-in-numpy">link provided by user1984065</a> in a comment.</p>
5
2016-10-08T03:34:52Z
[ "python", "numpy", "math", "memory", "matrix" ]
memory error while performing matrix multiplication
39,927,586
<p>As part of a project I'm working on, I need to calculate the mean squared error between <code>2m</code> vectors.</p> <p>Basically I two matrices <code>x</code> and <code>xhat</code>, both are size <code>m</code> by <code>n</code> and the vectors I'm interested in are the rows of these vectors.</p> <p>I calculate the MSE with this code</p> <pre><code>def cost(x, xhat): #mean squared error between x the data and xhat the output of the machine return (1.0/(2 * m)) * np.trace(np.dot(x-xhat,(x-xhat).T)) </code></pre> <p>It's working correctly, this formula is correct.</p> <p>The problem is that in my specific case, my <code>m</code> and <code>n</code> are very large. specifically, <code>m = 60000</code> and <code>n = 785</code>. So when I run my code and it enters this function, I get a memory error.</p> <p>Is there a better way to calculate the MSE? I'd rather avoid for loops and I lean heavily towards matrix multiplication, but matrix multiplication seems extremely wasteful here. Maybe something in numpy I'm not aware of?</p>
1
2016-10-08T00:51:42Z
39,930,177
<p>If you are going for performance as well, one alternative approach to compute sum of squared differences could be using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>, like so -</p> <pre><code>subs = x-xhat out = np.einsum('ij,ij',subs,subs) </code></pre>
1
2016-10-08T08:07:39Z
[ "python", "numpy", "math", "memory", "matrix" ]
Decreasing brightness in the bottom half of a photo
39,927,762
<p>I have a questions thats stumping me right now. I have to decrease the brightness of the bottom half of a picture. This is what I'm using so far. Its decreasing the brightness of the TOP half of my photo. How can I get it to decrease the bottom half? I know tat its somewhere in the third line I just can't figure it out. Any help would be greatly appreciated!</p> <pre><code>def bottomHalf(image): pixels = getPixels(image) for index in range(0,len(pixels)/2): pixel=pixels[index] value1=getRed(pixel) setRed(pixel,value1*.8) value2=getGreen(pixel) setGreen(pixel,value2*.8) value3=getBlue(pixel) setBlue(pixel,value3*.8) show(image) </code></pre>
0
2016-10-08T01:24:14Z
39,929,682
<p>I believe you need to do half the pixels, <em>"but starting from half way through them rather than from the beginning"</em>, if I can put it like that!</p> <p>So, replace this:</p> <pre><code>for index in range(0,len(pixels)/2): </code></pre> <p>with this:</p> <pre><code>for index in range(len(pixels)/2,len(pixels)): </code></pre> <p>Thanks to @MarkRansom for the correction.</p>
1
2016-10-08T07:02:46Z
[ "python", "image", "jes" ]
Why does my Python code fail unit testing?
39,927,779
<p>I have this challenge:</p> <blockquote> <p>Create a function called binary_converter. Inside the function, implement an algorithm to convert decimal numbers between 0 and 255 to their binary equivalents.</p> <p>For any invalid input, return string Invalid input</p> <p>Example: For number 5 return string 101</p> </blockquote> <p>Unit test code is below</p> <pre><code>import unittest class BinaryConverterTestCases(unittest.TestCase): def test_conversion_one(self): result = binary_converter(0) self.assertEqual(result, '0', msg='Invalid conversion') def test_conversion_two(self): result = binary_converter(62) self.assertEqual(result, '111110', msg='Invalid conversion') def test_no_negative_numbers(self): result = binary_converter(-1) self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed') def test_no_numbers_above_255(self): result = binary_converter(300) self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed') </code></pre> <p>my code goes below</p> <pre><code>def binary_converter(n): if(n==0): return "0" elif(n&gt;255): return "invalid input" elif(n &lt; 0): return "invalid input" else: ans="" while(n&gt;0): temp=n%2 ans=str(temp)+ans n=n/2 return ans </code></pre> <p>Unit test results</p> <pre><code>Total Specs: 4 Total Failures: 2 1. test_no_negative_numbers `Failure in line 19, in test_no_negative_numbers self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed') AssertionError: Input below 0 not allowed` 2. test_no_numbers_above_255 `Failure in line 23, in test_no_numbers_above_255 self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed') AssertionError: Input above 255 not allowed` </code></pre>
1
2016-10-08T01:27:36Z
39,927,802
<p>Comparing strings in Python cares cases.</p> <pre><code>&gt;&gt;&gt; 'invalid input' == 'Invalid input' False </code></pre> <p>You need to adjust test code or implementation code so that string literals matches exactly.</p> <pre><code>def test_no_negative_numbers(self): result = binary_converter(-1) self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed') ^--- (UPPERCASE) ... elif(n &lt; 0): return "invalid input" ^--- (lowercase) </code></pre>
2
2016-10-08T01:31:42Z
[ "python", "unit-testing" ]
Write floating point numbers without any decimal places
39,927,803
<p>I'm trying to have Python replicate some FORTRAN output of real values. My FORTRAN prints the real value as "31380.". I'm trying to replicate the same in Python--note that although I have no decimal places, I actually want the decimal point (period) to be printed. My current code is</p> <pre><code>htgm=31380. print '{:6.0f}'.format(htgm) </code></pre> <p>which yields "31380". What am I doing wrong?</p>
1
2016-10-08T01:31:42Z
39,927,829
<p>It is not possible to do it Python keeping the type of <code>htgm</code> as <code>float</code>. However if you are OK with making it as <code>str</code>, you may do:</p> <pre><code>htgm=31380. '{0:.0f}.'.format(htgm) # returns: '31380.' # OR, even simply '{}.'.format(int(htgm)) </code></pre>
1
2016-10-08T01:38:07Z
[ "python", "string", "format" ]
Write floating point numbers without any decimal places
39,927,803
<p>I'm trying to have Python replicate some FORTRAN output of real values. My FORTRAN prints the real value as "31380.". I'm trying to replicate the same in Python--note that although I have no decimal places, I actually want the decimal point (period) to be printed. My current code is</p> <pre><code>htgm=31380. print '{:6.0f}'.format(htgm) </code></pre> <p>which yields "31380". What am I doing wrong?</p>
1
2016-10-08T01:31:42Z
39,927,896
<p>Python format language includes an 'alternate' form for floats which forces the decimal point by using a '#' in the format string:</p> <pre><code>&gt;&gt;&gt; htgm=31380. &gt;&gt;&gt; format(htgm, '#.0f') '31380.' </code></pre> <p>Which is what I think you are looking for.<br> I thought <code>#g</code> would be what you wanted but for some reason python adds the <code>0</code> back on:</p> <pre><code>&gt;&gt;&gt; htgm=31380. &gt;&gt;&gt; format(htgm, 'g') '31380' &gt;&gt;&gt; format(htgm, '#g') '31380.0' </code></pre>
2
2016-10-08T01:51:29Z
[ "python", "string", "format" ]
Write floating point numbers without any decimal places
39,927,803
<p>I'm trying to have Python replicate some FORTRAN output of real values. My FORTRAN prints the real value as "31380.". I'm trying to replicate the same in Python--note that although I have no decimal places, I actually want the decimal point (period) to be printed. My current code is</p> <pre><code>htgm=31380. print '{:6.0f}'.format(htgm) </code></pre> <p>which yields "31380". What am I doing wrong?</p>
1
2016-10-08T01:31:42Z
39,927,926
<p>When you need to display the number, use:</p> <pre><code>print(str(htgm)[:-1]) </code></pre> <p>This notation will shave off the last '0'.</p>
0
2016-10-08T01:55:24Z
[ "python", "string", "format" ]
When i try to scrape details page for image I get an error
39,927,950
<p>I am trying to get the image of the details page from a website. I am using the rss 'links' function to get the links. This is my code</p> <pre><code>@app.task def pan_task(): url = 'http://feeds.example.com/reuters/technologyNews' name = 'noticiassin' live_leaks = [i for i in feedparser.parse(url).entries][:10] the_count = len(live_leaks) ky = feedparser.parse(url).keys() oky = [i.keys() for i in feedparser.parse(url).entries][1] # shows what I can pull def make_soup(url): def swappo(): user_one = ' "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0" ' user_two = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)" ' user_thr = ' "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" ' user_for = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0" ' agent_list = [user_one, user_two, user_thr, user_for] a = random.choice(agent_list) return a headers = { "user-agent": swappo(), "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "accept-encoding": "gzip,deflate,sdch", "accept-language": "en-US,en;q=0.8", } the_comments_page = requests.get(url, headers=headers) soupdata = BeautifulSoup(the_comments_page.text, 'html5lib') # comment = soupdata.find('a').get('src') # para = comment.find_all('p') # kids = [child.text for child in para] # blu = str(kids).strip('[]') return soupdata try: live_entries = [{'href': live_leak.links[0]['href']} for live_leak in live_leaks] o = make_soup(live_entries) except IndexError: print('error check logs') live_entries = [] return print(o) </code></pre> <p>but when I try I get this error</p> <pre><code>[2016-10-07 21:10:58,019: ERROR/MainProcess] Task blog.tasks.pan_task[f43ed360-c06e-4a4b-95ab-4f44a4564afa] raised unexpected: InvalidSchema("No connection adapters were found for '[{'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/AA1uAIpygjQ/us-apple-samsung-elec-appeal-idUSKCN1271LF'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/Nz28cqiuS0Y/us-google-pixel-advertising-idUSKCN12721U'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/POLoFj22hc4/us-yahoo-nsa-order-idUSKCN12800D'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/eF-XlhlQl-s/us-fcc-dataservices-idUSKCN1271RB'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/hNf9IQ3rXjw/us-autonomous-nauto-idUSKCN1271FX'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/NXkk5WfWVhM/us-sony-sensors-idUSKCN1270EC'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/gdBvoarqQro/us-yahoo-discrimination-lawsuit-idUSKCN12800K'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/nt8K--27bDg/us-thomsonreuters-ceo-idUSKCN1271DQ'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/f8z3eQg2Fpo/us-snapchat-ipo-idUSKCN12627S'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/rr4vdLsC11Y/us-samsung-elec-results-idUSKCN1262NO'}]'",) Traceback (most recent call last): File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/Users/ray/Desktop/myheroku/practice/src/blog/tasks.py", line 134, in pan_task o = make_soup(live_entries) File "/Users/ray/Desktop/myheroku/practice/src/blog/tasks.py", line 124, in make_soup the_comments_page = requests.get(url, headers=headers) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/requests/api.py", line 67, in get return request('get', url, params=params, **kwargs) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/requests/api.py", line 53, in request return session.request(method=method, url=url, **kwargs) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/requests/sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/requests/sessions.py", line 570, in send adapter = self.get_adapter(url=request.url) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/requests/sessions.py", line 644, in get_adapter raise InvalidSchema("No connection adapters were found for '%s'" % url) requests.exceptions.InvalidSchema: No connection adapters were found for '[{'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/AA1uAIpygjQ/us-apple-samsung-elec-appeal-idUSKCN1271LF'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/Nz28cqiuS0Y/us-google-pixel-advertising-idUSKCN12721U'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/POLoFj22hc4/us-yahoo-nsa-order-idUSKCN12800D'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/eF-XlhlQl-s/us-fcc-dataservices-idUSKCN1271RB'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/hNf9IQ3rXjw/us-autonomous-nauto-idUSKCN1271FX'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/NXkk5WfWVhM/us-sony-sensors-idUSKCN1270EC'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/gdBvoarqQro/us-yahoo-discrimination-lawsuit-idUSKCN12800K'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/nt8K--27bDg/us-thomsonreuters-ceo-idUSKCN1271DQ'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/f8z3eQg2Fpo/us-snapchat-ipo-idUSKCN12627S'}, {'href': 'http://feeds.reuters.com/~r/reuters/technologyNews/~3/rr4vdLsC11Y/us-samsung-elec-results-idUSKCN1262NO'}]' </code></pre> <p>whhy this not working? I use the function in another program.</p>
1
2016-10-08T01:59:28Z
39,928,098
<p>You need to do something like this:</p> <pre><code>@app.task def pan_task(): url = 'http://feeds.example.com/reuters/technologyNews' name = 'noticiassin' live_leaks = [i for i in feedparser.parse(url).entries][:10] the_count = len(live_leaks) ky = feedparser.parse(url).keys() oky = [i.keys() for i in feedparser.parse(url).entries][1] # shows what I can pull def make_soup(url): def swappo(): user_one = ' "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0" ' user_two = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)" ' user_thr = ' "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" ' user_for = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0" ' agent_list = [user_one, user_two, user_thr, user_for] a = random.choice(agent_list) return a headers = { "user-agent": swappo(), "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "accept-encoding": "gzip,deflate,sdch", "accept-language": "en-US,en;q=0.8", } the_comments_page = requests.get(url, headers=headers) soupdata = BeautifulSoup(the_comments_page.text, 'html5lib') # comment = soupdata.find('div') # para = comment.find_all('p') # kids = [child.text for child in para] # blu = str(kids).strip('[]') return soupdata live_entries = [] try: for live_leak in live_leaks: live_entries.append(make_soup(live_leak.links[0]['href'])) # Do what ever you need to do to o here except IndexError: print('error check logs') live_entries = [] return live_entries </code></pre>
-1
2016-10-08T02:28:46Z
[ "python", "parsing", "beautifulsoup", "screen-scraping", "feedparser" ]
What is the loss function that use the DNNRegressor?
39,928,035
<p>I am using <strong>DNNRegressor</strong> to train my model. I search in the documentation what is the loss function used by this wrapper but i don't find it. On the other hand, it is possible to change that loss function?.</p> <p>Thank you for your suggestions.</p>
0
2016-10-08T02:17:15Z
39,964,849
<p>It uses L2 loss (mean squared error) as defined in <a href="https://github.com/tensorflow/tensorflow/blob/754048a0453a04a761e112ae5d99c149eb9910dd/tensorflow/contrib/layers/python/layers/target_column.py" rel="nofollow">target_column.py</a>: </p> <pre><code>def regression_target(label_name=None, weight_column_name=None, target_dimension=1): """Creates a _TargetColumn for linear regression. Args: label_name: String, name of the key in label dict. Can be null if label is a tensor (single headed models). weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. target_dimension: dimension of the target for multilabels. Returns: An instance of _TargetColumn """ return _RegressionTargetColumn(loss_fn=_mean_squared_loss, label_name=label_name, weight_column_name=weight_column_name, target_dimension=target_dimension) </code></pre> <p>and currently API does not support any changes here. However, since it is open source - you can always modify the constructor to call different function internally, with different loss.</p>
1
2016-10-10T18:48:50Z
[ "python", "machine-learning", "neural-network", "tensorflow", "deep-learning" ]
"TypeError: can only concatenate tuple (not "float") to tuple"
39,928,048
<p>I am writing a program to open and read a txt file and go through loops each line. multiply values in 2nd column and 4th column and assign it to 5th column.</p> <pre><code>A 500.00 A 84.15 ? B 648.80 B 77.61 ? C 342.23 B 39.00 ? </code></pre> <p>this is part of codes I wrote, </p> <pre><code>for line in infile: a,b,c,d = line.split() e = eval(b) + eval(d) print("{0:20}${1:20}{2:20}${3:20}{4:20}".format(a,b,c,d,e),file=outfile) </code></pre> <p>I kept getting an error saying,</p> <blockquote> <p>File "C:/Users/hee lim/Desktop/readfile2.py", line 19, in main e = eval(b) + eval(d) TypeError: can only concatenate tuple (not "float") to tuple</p> </blockquote> <p>I covert strings into numbers using "eval" to multiply those numbers. I don't understand why it flags an error.</p> <p>thank you for your help. </p>
0
2016-10-08T02:19:55Z
39,928,077
<p>Looking at this information, I could only tell that the value returned by <code>eval</code> of <code>b</code> and <code>d</code> are of <code>float</code> and <code>tuple</code> type. And you can not do <code>+</code> on <code>float</code> and <code>tuple</code>. For example:</p> <pre><code>&gt;&gt;&gt; 5.0 + (2 ,3) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for +: 'float' and 'tuple' </code></pre> <p>For debugging, add <code>print line</code> at the start of <code>for</code> loop to see at what value it is raising error.</p>
0
2016-10-08T02:25:06Z
[ "python" ]
Install Python 3 to /usr/bin/ on macOS
39,928,053
<p>I installed python2.x and python3.x using homebrew and the executable python paths are listed below:</p> <pre><code>$ which python /Library/Frameworks/Python.framework/Versions/2.7/bin/python $ which python3 /Library/Frameworks/Python.framework/Versions/3.5/bin/python3 </code></pre> <p><br> It's quite too long and not so clean to write a shebang in a python code to make it runnable on Terminal:</p> <pre><code>#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python OR #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3 </code></pre> <p><br> I prefer</p> <pre><code>#!/usr/bin/python OR #!/usr/bin/python3 </code></pre> <p>My issue here is, how can I correcly move or reinstall python on macOS to <b>/usr/bin</b> such as <br> <code>/usr/bin/python</code> OR <code>/usr/bin/python3</code> <br><br>Instead of <br> <code>/Library/Frameworks/Python.framework/Versions/2.7/bin/python</code> <code>/Library/Frameworks/Python.framework/Versions/3.5/bin/python3</code></p>
0
2016-10-08T02:20:53Z
39,931,634
<p>Create a symbolic link in <code>/usr/bin/</code></p> <p>Open terminal and do:</p> <pre>$ sudo ln /Library/Frameworks/Python.framework/Versions/2.7/bin/python /usr/bin/python $ sudo ln /Library/Frameworks/Python.framework/Versions/3.5/bin/python3 /usr/bin/python3 </pre> <p>You can now do what you wanted to do.</p>
1
2016-10-08T11:07:39Z
[ "python", "osx", "python-3.x", "path" ]
How do I the value for a foreign key to show up in Django Rest
39,928,055
<p>I want my output json to show the value of a the record that the foreign key is pointing to instead of the key instead.</p> <p>For example i want this to show up:</p> <pre><code>[ { "id": 1, "brand": "ATL Motors", "package": "Full Page", "newspaper": "Gleaner", "cost": 22000, "objective": "Brand Awareness", "ad_date": "2016-10-01", "created_on": "2016-10-07T20:21:52Z" } </code></pre> <p>]</p> <p>Instead of this:</p> <pre><code>[ { "id": 1, "brand": 2, "package": "Full Page", "newspaper": 1, "cost": 22000, "objective": "Brand Awareness", "ad_date": "2016-10-01", "created_on": "2016-10-07T20:21:52Z" } ] </code></pre> <p>Here is my models.py file:</p> <pre><code>from django.db import models from django.utils import timezone class Brand(models.Model): name = models.CharField(max_length=100) description = models.TextField() website = models.URLField() created_on = models.DateTimeField(default=timezone.now()) def __str__(self): return self.name class Newspaper(models.Model): name = models.CharField(max_length=200) created_on = models.DateTimeField(default=timezone.now()) def __str__(self): return self.name class PurchasedAd(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) package = models.CharField(max_length=350) newspaper = models.ForeignKey(Newspaper, on_delete=models.CASCADE) cost = models.IntegerField() objective = models.TextField() ad_date = models.DateField() created_on = models.DateTimeField(default=timezone.now()) def __str__(self): string = "{} - {}".format(self.brand, self.objective) return string </code></pre> <p>Here is my serializer.py file:</p> <pre><code>from rest_framework import serializers from . import models class BrandSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'name', 'description', 'website', 'created_on', ) model = models.Brand class PurchasedAdSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'brand', 'package', 'newspaper', 'cost', 'objective', 'ad_date', 'created_on', ) model = models.PurchasedAd </code></pre> <p>Here is my views.py file:</p> <pre><code>from rest_framework import generics from . import models from . import serializers class ListBrand(generics.ListAPIView): queryset = models.Brand.objects.all() serializer_class = serializers.BrandSerializer class ListAds(generics.ListAPIView): queryset = models.PurchasedAd.objects.all() serializer_class = serializers.PurchasedAdSerializer </code></pre> <p>PLEASE HELP!!</p>
0
2016-10-08T02:21:09Z
39,928,830
<p>You can use <a href="http://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield" rel="nofollow">StringRelatedField</a></p> <blockquote> <p>StringRelatedField may be used to represent the target of the relationship using its <strong>unicode</strong> method.</p> </blockquote> <pre><code>class PurchasedAdSerializer(serializers.ModelSerializer): newspaper = serializers.StringRelatedField() class Meta: fields = ( 'id', 'brand', 'package', 'newspaper', 'cost', 'objective', 'ad_date', 'created_on', ) model = models.PurchasedAd </code></pre>
0
2016-10-08T04:59:12Z
[ "python", "django", "django-rest-framework" ]
Verification of ssl certificates failed after compiling .py to .exe
39,928,062
<p>I have a script that reads to a URL. It works fine if I run it to cmd using <code>python app.py</code>. But after compiling it using py2exe and running the <code>.exe</code> I am getting this error</p> <pre><code>entering main now..... Traceback (most recent call last): File "strtojson.py", line 257, in &lt;module&gt; File "strtojson.py", line 209, in main File "requests\api.pyc", line 70, in get File "requests\api.pyc", line 56, in request File "requests\sessions.pyc", line 475, in request File "requests\sessions.pyc", line 596, in send File "requests\adapters.pyc", line 497, in send requests.exceptions.SSLError: [Errno 2] No such file or directory </code></pre> <p>Here is how I access the site. </p> <pre><code>url = 'https://www.sec.gov/cgi-bin/browse-edgar?company=&amp;CIK=&amp;type=8-k&amp;owner=include&amp;count=100&amp;action=getcurrent' response = requests.get(url) html = response.content soup = BeautifulSoup(html, "html.parser") </code></pre> <p>And here is my <code>setup.py</code></p> <pre><code>from distutils.core import setup import py2exe setup(console=['strtojson.py'], options = {'py2exe' : {'packages': ['bs4', 'requests']}}) </code></pre> <p>Im using Python 2.7.12 on Win 7 64bit</p>
0
2016-10-08T02:22:09Z
39,928,824
<p>My guess is that Python will not find the trusted CA (needed to validate the server certificates) anymore because they are not included in the exe. In this case using <code>requests.get</code> with <code>verify=False</code> should work. </p> <p>But this should only be done to verify that this is really the cause of the problem. The better fix would then by to put the necessary trusted CA into a file, ship this file together with the exe and use <code>verify='trusted-ca.pem'</code> then. You can get a widely used collection of trusted CA at <a href="https://curl.haxx.se/docs/caextract.html" rel="nofollow">https://curl.haxx.se/docs/caextract.html</a>.</p> <p>While it would be nice to make <code>requests</code> use some string as trusted CA I don't think that this is supported. You can of course include the trusted CA as a string inside the exe and then create a temporary file from it before calling <code>requests.get(..., verify='temporary-ca-file.pem')</code>.</p>
0
2016-10-08T04:58:27Z
[ "python", "ssl", "ssl-certificate", "python-requests" ]
Karatsuba Infinite Recursion - Python
39,928,083
<p>Beginner here. I've spent most of the day working on the Karatsuba Algorithm just because I thought it would be fruitful. I've seen similar questions on here, but they are in other languages and seem strangely complex. The following is my code. The minute it hits the recursive call to ac, it just keeps on recursing. It's as if it never hits the base case. If anyone could be so kind as to offer some insight as to where things are going wrong, it would be greatly appreciated. For this code, you should assume I'm multiplying 2, base-10, four-digit numbers.</p> <pre><code>def karatsuba(x, y): if len(str(x)) == 1 or len(str(y)) == 1: return (x * y) else: n = (max(len(str(x)), len(str(y)))) a = x / 10**(n / 2) b = x % 10**(n / 2) c = y / 10**(n / 2) d = y % 10**(n / 2) ac = karatsuba(a, c) ad = karatsuba(a, d) bc = karatsuba(b, c) bd = karatsuba(b, d) product = (10**n*(ac) + 10**(n/2)*(ad + bc) + bd) return product print (karatsuba(1234, 5678)) </code></pre>
0
2016-10-08T02:26:15Z
39,928,285
<p>Do you want integer division? In this case, you should use:</p> <pre><code>a = x // 10 ** (n / 2) </code></pre> <p>and</p> <pre><code>c = y // 10 ** (n / 2) </code></pre> <p>Otherwise, your program will be feeding through decimals to your function which I assume is not intended.</p> <p>I'm also a beginner, feel free to correct me.</p>
1
2016-10-08T03:07:29Z
[ "python", "algorithm", "recursion", "karatsuba" ]
Karatsuba Infinite Recursion - Python
39,928,083
<p>Beginner here. I've spent most of the day working on the Karatsuba Algorithm just because I thought it would be fruitful. I've seen similar questions on here, but they are in other languages and seem strangely complex. The following is my code. The minute it hits the recursive call to ac, it just keeps on recursing. It's as if it never hits the base case. If anyone could be so kind as to offer some insight as to where things are going wrong, it would be greatly appreciated. For this code, you should assume I'm multiplying 2, base-10, four-digit numbers.</p> <pre><code>def karatsuba(x, y): if len(str(x)) == 1 or len(str(y)) == 1: return (x * y) else: n = (max(len(str(x)), len(str(y)))) a = x / 10**(n / 2) b = x % 10**(n / 2) c = y / 10**(n / 2) d = y % 10**(n / 2) ac = karatsuba(a, c) ad = karatsuba(a, d) bc = karatsuba(b, c) bd = karatsuba(b, d) product = (10**n*(ac) + 10**(n/2)*(ad + bc) + bd) return product print (karatsuba(1234, 5678)) </code></pre>
0
2016-10-08T02:26:15Z
39,928,519
<p>Just fixing your code with integer divisions made it work correctly but here's a slight different version using 3 recursive calls (in base 10):</p> <pre><code>def karatsuba(x, y): if x &lt; 10 or y &lt; 10: return x * y n = max(len(str(x)), len(str(y))) // 2 p = 10**n a, b = divmod(x, p) c, d = divmod(y, p) ac = karatsuba(a, c) bd = karatsuba(b, d) abcd = karatsuba(a+b, c+d) - ac - bd return (ac*p + abcd)*p + bd </code></pre> <p>But it is much faster operating in binary and using bit-twiddling:</p> <pre><code>def karatsuba(x, y): if x &lt; 16 or y &lt; 16: return x * y n = max(x.bit_length(), y.bit_length()) // 2 mask = (1 &lt;&lt; n) - 1 a, b = x &gt;&gt; n, x &amp; mask c, d = y &gt;&gt; n, y &amp; mask ac = karatsuba(a, c) bd = karatsuba(b, d) abcd = karatsuba(a+b, c+d) - ac - bd return (((ac &lt;&lt; n) + abcd) &lt;&lt; n) + bd </code></pre>
1
2016-10-08T03:57:39Z
[ "python", "algorithm", "recursion", "karatsuba" ]
Is there a more recursive way to do this?
39,928,220
<p>I have the following code:</p> <pre><code>{% if thing.parent.parent.parent.link %} &lt;a href="/y/{{ thing.parent.parent.parent.link }}"&gt;{{ thing.parent.parent.parent.name }}&lt;/a&gt; {% endif %} {% if thing.parent.parent.link %} &lt;a href="/y/{{ thing.parent.parent.link }}"&gt;{{ thing.parent.parent.name }}&lt;/a&gt; {% endif %} {% if thing.parent.link %} &lt;a href="/y/{{ thing.parent.link }}"&gt;{{ thing.parent.name }}&lt;/a&gt; {% endif %} </code></pre> <p>The key thing that changes in this non-recursive code, is simply adding a .parent to the link/link text.</p> <p>I need to do this 20 times in total, as you can see, it's quite ugly to repeat and quite repetitive. Is there a more recursive and nicer way of doing it using django's template framework?</p>
0
2016-10-08T02:53:52Z
39,928,569
<p>Return a list in your context and then you can use an iterative approach:</p> <pre><code>{% for parent in parents %} &lt;a href="/y/{{ parent.link }}"&gt;{{ parent.name }}&lt;/a&gt; {% endfor %} </code></pre> <p>Since nothing special has to be done if it is a child (as you mentioned, the only difference is link and name), you can just convert the things' parents to a list. I cannot give an exact method to do this without knowing more about your data structures, but maybe this will give you an idea:</p> <pre><code> parents = [] for thing in things: node = thing while hasattr(node, 'parent'): parents.append(node.parent) node = node.parent </code></pre>
2
2016-10-08T04:07:02Z
[ "python", "django", "recursion", "django-templates" ]
How to extract number from text in python?
39,928,255
<p>I have the string listed below</p> <pre><code>str = ['"Consumers_Of_Product": {"count": 13115}'] </code></pre> <p>How can I extract the number 13115 as it will change, so that it will always equal var. In other words how do I extract this number from this string?</p> <p>Most things I've done previously have not worked and I think that is due to the syntax. I'm running Python 2.7.</p>
1
2016-10-08T03:01:26Z
39,928,276
<p>Use <code>ast.literal_eval</code> on the single element in that list (which you shouldn't call <code>str</code> because it masks the built-in, and it isn't a string anyway), within curly braces (as it seems to be a dictionary element):</p> <pre><code>&gt;&gt;&gt; import ast &gt;&gt;&gt; s = ['"Consumers_Of_Product": {"count": 13115}'] &gt;&gt;&gt; ast.literal_eval('{{{}}}'.format(s[0])) {'Consumers_Of_Product': {'count': 13115}} </code></pre>
2
2016-10-08T03:06:30Z
[ "python", "string", "python-2.7", "integer" ]
How to extract number from text in python?
39,928,255
<p>I have the string listed below</p> <pre><code>str = ['"Consumers_Of_Product": {"count": 13115}'] </code></pre> <p>How can I extract the number 13115 as it will change, so that it will always equal var. In other words how do I extract this number from this string?</p> <p>Most things I've done previously have not worked and I think that is due to the syntax. I'm running Python 2.7.</p>
1
2016-10-08T03:01:26Z
39,928,323
<p>If you just want to extract that number, provided there are no other numbers in that string, you can use <code>regex</code>. I renamed <code>str</code> to be <code>s</code> for the reason mentioned in @TigerhawkT3 answer.</p> <pre><code>import re s = ['"Consumers_Of_Product": {"count": 13115}'] num = re.findall('\d+', s[0]) print(num[0]) 13115 </code></pre>
1
2016-10-08T03:17:18Z
[ "python", "string", "python-2.7", "integer" ]
How to extract number from text in python?
39,928,255
<p>I have the string listed below</p> <pre><code>str = ['"Consumers_Of_Product": {"count": 13115}'] </code></pre> <p>How can I extract the number 13115 as it will change, so that it will always equal var. In other words how do I extract this number from this string?</p> <p>Most things I've done previously have not worked and I think that is due to the syntax. I'm running Python 2.7.</p>
1
2016-10-08T03:01:26Z
39,928,352
<p>You have <a href="http://stackoverflow.com/questions/9949533/python-eval-vs-ast-literal-eval-vs-json-decode">3 options</a></p> <p>But it's recommended to use <code>json</code> lib </p> <pre><code>import json s = ['"Consumers_Of_Product": {"count": 13115}'] s[0] = '{' + s[0] + '}' my_var = json.loads(s[0]) # this is where you translate from string to dict print my_var['Consumers_Of_Product']['count'] # 13115 </code></pre> <blockquote> <p>remembering what <a href="http://stackoverflow.com/questions/39928255/how-to-extract-number-from-text-in-python/39928276#39928276">TigerhawkT3</a> said about why you shouldn't use <code>str</code></p> </blockquote>
0
2016-10-08T03:22:39Z
[ "python", "string", "python-2.7", "integer" ]
How to extract number from text in python?
39,928,255
<p>I have the string listed below</p> <pre><code>str = ['"Consumers_Of_Product": {"count": 13115}'] </code></pre> <p>How can I extract the number 13115 as it will change, so that it will always equal var. In other words how do I extract this number from this string?</p> <p>Most things I've done previously have not worked and I think that is due to the syntax. I'm running Python 2.7.</p>
1
2016-10-08T03:01:26Z
39,928,356
<p>You can use <code>regular expression</code> to extract anything you want from a string. Here is a link about <a href="https://docs.python.org/2/howto/regex.html" rel="nofollow">HOW TO use Regular expression in python</a></p> <p>sample code here:</p> <pre><code>import re m = re.search(r'(\d+)', s[0]) if m: print m.group() else: print 'nothing found' </code></pre> <p>Your string looks something like a <code>JSON</code> string, so if you are dealing with json string, you can make use of <code>json</code> package to extract the value for field <code>count</code></p> <p>sample code here (you need to wrap your string with <code>{}</code> or array <code>[]</code> ):</p> <pre><code>import json obj = json.loads('{"Consumers_Of_Product": {"count": 13115}}') print(obj['Consumers_Of_Product']['count']) </code></pre>
0
2016-10-08T03:22:57Z
[ "python", "string", "python-2.7", "integer" ]
how to convert all columns in the .csv file from numeric to categorical in Python
39,928,264
<pre><code>data[].astype('categorical') </code></pre> <p>there are 51 columns in my csv file, do I need to add all 51 column namesin the square brackets? I need all 51 columns which are in int64 to be categorical </p>
1
2016-10-08T03:03:09Z
39,928,460
<p>You can get the column names into a list, then loop to change the type of each column.</p> <pre><code>import pandas as pd import numpy as np # create example dataframe cats = ['A', 'B', 'C', 'D', 'E'] int_matrix = np.random.randint(10, size=(7,5)) df = pd.DataFrame(data = int_matrix, columns=cats) print("Original example data\n") print(df) print(df.dtypes) # get column names of data frame in a list col_names = list(df) print("\nNames of dataframe columns") print(col_names) # loop to change each column to category type for col in col_names: df[col] = df[col].astype('category',copy=False) print("\nExample data changed to category type") print(df) print(df.dtypes) </code></pre> <p>The output of this little program is:</p> <pre><code>Original example data A B C D E 0 0 4 9 2 9 1 2 5 2 4 1 2 1 1 0 5 7 3 1 2 5 4 0 4 9 2 6 5 3 5 3 3 2 1 7 6 6 0 8 7 3 A int32 B int32 C int32 D int32 E int32 dtype: object Names of dataframe columns ['A', 'B', 'C', 'D', 'E'] Example data changed to category type A B C D E 0 0 4 9 2 9 1 2 5 2 4 1 2 1 1 0 5 7 3 1 2 5 4 0 4 9 2 6 5 3 5 3 3 2 1 7 6 6 0 8 7 3 A category B category C category D category E category dtype: object </code></pre>
0
2016-10-08T03:46:38Z
[ "python" ]
How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python)
39,928,273
<p>I have the following data in a csv file:</p> <pre><code>from StringIO import StringIO import pandas as pd the_data = """ ABC,2016-6-9 0:00,95,{'//PurpleCar': [115L], '//YellowCar': [403L], '//BlueCar': [16L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-10 0:00,0,{'//PurpleCar': [219L], '//YellowCar': [381L], '//BlueCar': [90L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-11 0:00,0,{'//PurpleCar': [817L], '//YellowCar': [21L], '//BlueCar': [31L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-12 0:00,0,{'//PurpleCar': [80L], '//YellowCar': [2011L], '//BlueCar': [8888L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-13 0:00,0,{'//PurpleCar': [32L], '//YellowCar': [15L], '//BlueCar': [4L], '//WhiteCar-XYZ': [0L]} DEF,2016-6-16 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-17 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-18 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-19 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-20 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} """ </code></pre> <p>I read the file into a Pandas data frame, as follows:</p> <pre><code>df = pd.read_csv(StringIO(the_data), sep=',') </code></pre> <p>Then, I add a few column headers, as follows:</p> <pre><code>df.columns = ['Company', 'Date', 'Volume', 'Car1', 'Car2', 'Car3', 'Car4'] </code></pre> <p>I see that the data is coming through as follows:</p> <pre><code>ABC,2016-6-9 0:00,95,{'//PurpleCar': [115L], '//YellowCar': [403L], '//BlueCar': [16L], '//WhiteCar-XYZ': [0L] </code></pre> <p>But, I'd like to see the data <strong>without</strong> any of the following:</p> <p>a) the curly braces (<code>"{"</code>) at the beginning and the curly brace (<code>"}"</code>) at the end of the dictionary</p> <p>b) the "L" after the numerical values</p> <p>c) the square brackets (<code>"["</code> and <code>"]"</code>) surrounding the numerical values</p> <p>d) the apostrophes surrounding the keys</p> <p>Ideally, the data would be transformed as follows:</p> <pre><code>ABC,2016-6-9 0:00,95,//PurpleCar: 115, //YellowCar: 403, //BlueCar: 16, //WhiteCar-XYZ: 0 </code></pre> <p>I tried this:</p> <pre><code>df['Car1'] = df['Car1'].str.strip(['{', '}', '[', 'L]']) </code></pre> <p>But, it doesn't work. It results in the 'Car1' column becoming NaN values.</p> <p>Is it possible to transform the data frame such that each row of the data frame reads as follows?</p> <pre><code>ABC,2016-6-9 0:00,95,//PurpleCar: 115, //YellowCar: 403, //BlueCar: 16, //WhiteCar-XYZ: 0 </code></pre> <p>Thanks!</p> <p><strong>UPDATE</strong>:</p> <p>Using the following regular expression:</p> <pre><code>df['Car1'] = df['Car1'].str.replace(r'\D+', '').astype('int') </code></pre> <p>Results in this:</p> <pre><code>ABC,2016-6-9 0:00,95, 115 , //YellowCar: 403, //BlueCar: 16, //WhiteCar-XYZ: 0 </code></pre> <p>We lose '//PurpleCar' and are left with only the numeric value of 115. That's a good start, but it would be great if we can see the '//PurpleCar' key, too.</p> <p>Any ideas?</p> <hr> <p><strong>UPDATE 2:</strong></p> <p>Based on the comments by piRSquared and HYRY, my goal is to be able to plot the numerical results. So, I would like to have the data frame look as follows:</p> <pre><code> Company Date PurpleCar YellowCar BlueCar WhiteCar 0 ABC 2016-6-9 0:00 115 403 16 0 1 ABC 2016-6-10 0:00 219 381 90 0 2 ABC 2016-6-11 0:00 817 21 31 0 3 ABC 2016-6-12 0:00 80 2011 8888 0 4 ABC 2016-6-13 0:00 32 15 4 0 5 DEF 2016-6-16 0:00 32 15 4 0 6 DEF 2016-6-17 0:00 32 15 4 0 7 DEF 2016-6-18 0:00 32 15 4 0 8 DEF 2016-6-19 0:00 32 15 4 0 9 DEF 2016-6-20 0:00 32 15 4 0 </code></pre> <p><strong>* UPDATE 3: *</strong></p> <p>The data originally posted had a small mistake. Here is the data:</p> <pre><code>the_data = """ ABC,2016-6-9 0:00,95,"{'//Purple': [115L], '//Yellow': [403L], '//Blue': [16L], '//White-XYZ': [0L]}" ABC,2016-6-10 0:00,0,"{'//Purple': [219L], '//Yellow': [381L], '//Blue': [90L], '//White-XYZ': [0L]}" ABC,2016-6-11 0:00,0,"{'//Purple': [817L], '//Yellow': [21L], '//Blue': [31L], '//White-XYZ': [0L]}" ABC,2016-6-12 0:00,0,"{'//Purple': [80L], '//Yellow': [2011L], '//Blue': [8888L], '//White-XYZ': [0L]}" ABC,2016-6-13 0:00,0,"{'//Purple': [32L], '//Yellow': [15L], '//Blue': [4L], '//White-XYZ': [0L]}" DEF,2016-6-16 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [3L]}" DEF,2016-6-17 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [0L]}" DEF,2016-6-18 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [7L]}" DEF,2016-6-19 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [14L]}" DEF,2016-6-20 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [21L]}" """ </code></pre> <p>The difference between this data and the original data is the apostrophes <code>(")</code> before the opening curly brace (<code>"{"</code>) and after the closing curly brace (<code>"}"</code>).</p>
1
2016-10-08T03:04:57Z
39,930,002
<p>this should do the trick</p> <pre><code>s = pd.read_csv(StringIO(the_data), sep='|', header=None, squeeze=True) left = s.str.split(',').str[:3].apply(pd.Series) left.columns = ['Company', 'Date', 'Volume'] right = s.str.split(',').str[3:].str.join(',') \ .str.replace(r'[\[\]\{\}\']', '') \ .str.replace(r'(:\s+\d+)L', r'\1') \ .str.split(',', expand=True) right.columns = ['Car{}'.format(i) for i in range(1, 5)] pd.concat([left, right], axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/eO71W.png" rel="nofollow"><img src="http://i.stack.imgur.com/eO71W.png" alt="enter image description here"></a></p>
0
2016-10-08T07:46:12Z
[ "python", "regex", "pandas" ]
How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python)
39,928,273
<p>I have the following data in a csv file:</p> <pre><code>from StringIO import StringIO import pandas as pd the_data = """ ABC,2016-6-9 0:00,95,{'//PurpleCar': [115L], '//YellowCar': [403L], '//BlueCar': [16L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-10 0:00,0,{'//PurpleCar': [219L], '//YellowCar': [381L], '//BlueCar': [90L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-11 0:00,0,{'//PurpleCar': [817L], '//YellowCar': [21L], '//BlueCar': [31L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-12 0:00,0,{'//PurpleCar': [80L], '//YellowCar': [2011L], '//BlueCar': [8888L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-13 0:00,0,{'//PurpleCar': [32L], '//YellowCar': [15L], '//BlueCar': [4L], '//WhiteCar-XYZ': [0L]} DEF,2016-6-16 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-17 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-18 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-19 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-20 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} """ </code></pre> <p>I read the file into a Pandas data frame, as follows:</p> <pre><code>df = pd.read_csv(StringIO(the_data), sep=',') </code></pre> <p>Then, I add a few column headers, as follows:</p> <pre><code>df.columns = ['Company', 'Date', 'Volume', 'Car1', 'Car2', 'Car3', 'Car4'] </code></pre> <p>I see that the data is coming through as follows:</p> <pre><code>ABC,2016-6-9 0:00,95,{'//PurpleCar': [115L], '//YellowCar': [403L], '//BlueCar': [16L], '//WhiteCar-XYZ': [0L] </code></pre> <p>But, I'd like to see the data <strong>without</strong> any of the following:</p> <p>a) the curly braces (<code>"{"</code>) at the beginning and the curly brace (<code>"}"</code>) at the end of the dictionary</p> <p>b) the "L" after the numerical values</p> <p>c) the square brackets (<code>"["</code> and <code>"]"</code>) surrounding the numerical values</p> <p>d) the apostrophes surrounding the keys</p> <p>Ideally, the data would be transformed as follows:</p> <pre><code>ABC,2016-6-9 0:00,95,//PurpleCar: 115, //YellowCar: 403, //BlueCar: 16, //WhiteCar-XYZ: 0 </code></pre> <p>I tried this:</p> <pre><code>df['Car1'] = df['Car1'].str.strip(['{', '}', '[', 'L]']) </code></pre> <p>But, it doesn't work. It results in the 'Car1' column becoming NaN values.</p> <p>Is it possible to transform the data frame such that each row of the data frame reads as follows?</p> <pre><code>ABC,2016-6-9 0:00,95,//PurpleCar: 115, //YellowCar: 403, //BlueCar: 16, //WhiteCar-XYZ: 0 </code></pre> <p>Thanks!</p> <p><strong>UPDATE</strong>:</p> <p>Using the following regular expression:</p> <pre><code>df['Car1'] = df['Car1'].str.replace(r'\D+', '').astype('int') </code></pre> <p>Results in this:</p> <pre><code>ABC,2016-6-9 0:00,95, 115 , //YellowCar: 403, //BlueCar: 16, //WhiteCar-XYZ: 0 </code></pre> <p>We lose '//PurpleCar' and are left with only the numeric value of 115. That's a good start, but it would be great if we can see the '//PurpleCar' key, too.</p> <p>Any ideas?</p> <hr> <p><strong>UPDATE 2:</strong></p> <p>Based on the comments by piRSquared and HYRY, my goal is to be able to plot the numerical results. So, I would like to have the data frame look as follows:</p> <pre><code> Company Date PurpleCar YellowCar BlueCar WhiteCar 0 ABC 2016-6-9 0:00 115 403 16 0 1 ABC 2016-6-10 0:00 219 381 90 0 2 ABC 2016-6-11 0:00 817 21 31 0 3 ABC 2016-6-12 0:00 80 2011 8888 0 4 ABC 2016-6-13 0:00 32 15 4 0 5 DEF 2016-6-16 0:00 32 15 4 0 6 DEF 2016-6-17 0:00 32 15 4 0 7 DEF 2016-6-18 0:00 32 15 4 0 8 DEF 2016-6-19 0:00 32 15 4 0 9 DEF 2016-6-20 0:00 32 15 4 0 </code></pre> <p><strong>* UPDATE 3: *</strong></p> <p>The data originally posted had a small mistake. Here is the data:</p> <pre><code>the_data = """ ABC,2016-6-9 0:00,95,"{'//Purple': [115L], '//Yellow': [403L], '//Blue': [16L], '//White-XYZ': [0L]}" ABC,2016-6-10 0:00,0,"{'//Purple': [219L], '//Yellow': [381L], '//Blue': [90L], '//White-XYZ': [0L]}" ABC,2016-6-11 0:00,0,"{'//Purple': [817L], '//Yellow': [21L], '//Blue': [31L], '//White-XYZ': [0L]}" ABC,2016-6-12 0:00,0,"{'//Purple': [80L], '//Yellow': [2011L], '//Blue': [8888L], '//White-XYZ': [0L]}" ABC,2016-6-13 0:00,0,"{'//Purple': [32L], '//Yellow': [15L], '//Blue': [4L], '//White-XYZ': [0L]}" DEF,2016-6-16 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [3L]}" DEF,2016-6-17 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [0L]}" DEF,2016-6-18 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [7L]}" DEF,2016-6-19 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [14L]}" DEF,2016-6-20 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [21L]}" """ </code></pre> <p>The difference between this data and the original data is the apostrophes <code>(")</code> before the opening curly brace (<code>"{"</code>) and after the closing curly brace (<code>"}"</code>).</p>
1
2016-10-08T03:04:57Z
39,931,830
<p>I think it's better to conver the strings into two columns:</p> <pre><code>from io import StringIO import pandas as pd df = pd.read_csv(StringIO(the_data), sep=',', header=None) df.columns = ['Company','Date','Volume','Car1','Car2','Car3','Car4'] cars = ["Car1", "Car2", "Car3", "Car4"] pattern = r"//(?P&lt;color&gt;.+?)':.*?(?P&lt;value&gt;\d+)" df2 = pd.concat([df[col].str .extract(pattern) .assign(value=lambda self: pd.to_numeric(self["value"])) for col in cars], axis=1, keys=cars) </code></pre> <p>the result:</p> <pre><code> Car1 Car2 Car3 Car4 color value color value color value color value 0 PurpleCar 115 YellowCar 403 BlueCar 16 WhiteCar-XYZ 0 1 PurpleCar 219 YellowCar 381 BlueCar 90 WhiteCar-XYZ 0 2 PurpleCar 817 YellowCar 21 BlueCar 31 WhiteCar-XYZ 0 3 PurpleCar 80 YellowCar 2011 BlueCar 8888 WhiteCar-XYZ 0 4 PurpleCar 32 YellowCar 15 BlueCar 4 WhiteCar-XYZ 0 5 PurpleCar 32 BlackCar 15 PinkCar 4 NPO-GreenCar 0 6 PurpleCar 32 BlackCar 15 PinkCar 4 NPO-GreenCar 0 7 PurpleCar 32 BlackCar 15 PinkCar 4 NPO-GreenCar 0 8 PurpleCar 32 BlackCar 15 PinkCar 4 NPO-GreenCar 0 9 PurpleCar 32 BlackCar 15 PinkCar 4 NPO-GreenCar 0 </code></pre>
0
2016-10-08T11:30:58Z
[ "python", "regex", "pandas" ]
How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python)
39,928,273
<p>I have the following data in a csv file:</p> <pre><code>from StringIO import StringIO import pandas as pd the_data = """ ABC,2016-6-9 0:00,95,{'//PurpleCar': [115L], '//YellowCar': [403L], '//BlueCar': [16L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-10 0:00,0,{'//PurpleCar': [219L], '//YellowCar': [381L], '//BlueCar': [90L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-11 0:00,0,{'//PurpleCar': [817L], '//YellowCar': [21L], '//BlueCar': [31L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-12 0:00,0,{'//PurpleCar': [80L], '//YellowCar': [2011L], '//BlueCar': [8888L], '//WhiteCar-XYZ': [0L]} ABC,2016-6-13 0:00,0,{'//PurpleCar': [32L], '//YellowCar': [15L], '//BlueCar': [4L], '//WhiteCar-XYZ': [0L]} DEF,2016-6-16 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-17 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-18 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-19 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} DEF,2016-6-20 0:00,0,{'//PurpleCar': [32L], '//BlackCar': [15L], '//PinkCar': [4L], '//NPO-GreenCar': [0L]} """ </code></pre> <p>I read the file into a Pandas data frame, as follows:</p> <pre><code>df = pd.read_csv(StringIO(the_data), sep=',') </code></pre> <p>Then, I add a few column headers, as follows:</p> <pre><code>df.columns = ['Company', 'Date', 'Volume', 'Car1', 'Car2', 'Car3', 'Car4'] </code></pre> <p>I see that the data is coming through as follows:</p> <pre><code>ABC,2016-6-9 0:00,95,{'//PurpleCar': [115L], '//YellowCar': [403L], '//BlueCar': [16L], '//WhiteCar-XYZ': [0L] </code></pre> <p>But, I'd like to see the data <strong>without</strong> any of the following:</p> <p>a) the curly braces (<code>"{"</code>) at the beginning and the curly brace (<code>"}"</code>) at the end of the dictionary</p> <p>b) the "L" after the numerical values</p> <p>c) the square brackets (<code>"["</code> and <code>"]"</code>) surrounding the numerical values</p> <p>d) the apostrophes surrounding the keys</p> <p>Ideally, the data would be transformed as follows:</p> <pre><code>ABC,2016-6-9 0:00,95,//PurpleCar: 115, //YellowCar: 403, //BlueCar: 16, //WhiteCar-XYZ: 0 </code></pre> <p>I tried this:</p> <pre><code>df['Car1'] = df['Car1'].str.strip(['{', '}', '[', 'L]']) </code></pre> <p>But, it doesn't work. It results in the 'Car1' column becoming NaN values.</p> <p>Is it possible to transform the data frame such that each row of the data frame reads as follows?</p> <pre><code>ABC,2016-6-9 0:00,95,//PurpleCar: 115, //YellowCar: 403, //BlueCar: 16, //WhiteCar-XYZ: 0 </code></pre> <p>Thanks!</p> <p><strong>UPDATE</strong>:</p> <p>Using the following regular expression:</p> <pre><code>df['Car1'] = df['Car1'].str.replace(r'\D+', '').astype('int') </code></pre> <p>Results in this:</p> <pre><code>ABC,2016-6-9 0:00,95, 115 , //YellowCar: 403, //BlueCar: 16, //WhiteCar-XYZ: 0 </code></pre> <p>We lose '//PurpleCar' and are left with only the numeric value of 115. That's a good start, but it would be great if we can see the '//PurpleCar' key, too.</p> <p>Any ideas?</p> <hr> <p><strong>UPDATE 2:</strong></p> <p>Based on the comments by piRSquared and HYRY, my goal is to be able to plot the numerical results. So, I would like to have the data frame look as follows:</p> <pre><code> Company Date PurpleCar YellowCar BlueCar WhiteCar 0 ABC 2016-6-9 0:00 115 403 16 0 1 ABC 2016-6-10 0:00 219 381 90 0 2 ABC 2016-6-11 0:00 817 21 31 0 3 ABC 2016-6-12 0:00 80 2011 8888 0 4 ABC 2016-6-13 0:00 32 15 4 0 5 DEF 2016-6-16 0:00 32 15 4 0 6 DEF 2016-6-17 0:00 32 15 4 0 7 DEF 2016-6-18 0:00 32 15 4 0 8 DEF 2016-6-19 0:00 32 15 4 0 9 DEF 2016-6-20 0:00 32 15 4 0 </code></pre> <p><strong>* UPDATE 3: *</strong></p> <p>The data originally posted had a small mistake. Here is the data:</p> <pre><code>the_data = """ ABC,2016-6-9 0:00,95,"{'//Purple': [115L], '//Yellow': [403L], '//Blue': [16L], '//White-XYZ': [0L]}" ABC,2016-6-10 0:00,0,"{'//Purple': [219L], '//Yellow': [381L], '//Blue': [90L], '//White-XYZ': [0L]}" ABC,2016-6-11 0:00,0,"{'//Purple': [817L], '//Yellow': [21L], '//Blue': [31L], '//White-XYZ': [0L]}" ABC,2016-6-12 0:00,0,"{'//Purple': [80L], '//Yellow': [2011L], '//Blue': [8888L], '//White-XYZ': [0L]}" ABC,2016-6-13 0:00,0,"{'//Purple': [32L], '//Yellow': [15L], '//Blue': [4L], '//White-XYZ': [0L]}" DEF,2016-6-16 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [3L]}" DEF,2016-6-17 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [0L]}" DEF,2016-6-18 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [7L]}" DEF,2016-6-19 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [14L]}" DEF,2016-6-20 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [21L]}" """ </code></pre> <p>The difference between this data and the original data is the apostrophes <code>(")</code> before the opening curly brace (<code>"{"</code>) and after the closing curly brace (<code>"}"</code>).</p>
1
2016-10-08T03:04:57Z
39,936,698
<p><strong>Edit:</strong> The file seems to be actually an escaped CSV so we don't need a custom parsing for this part.</p> <p><strike>As @Blckknght points out in the comment, the file is not a valid CSV. I'll make some assumptions in my answer. They are</p> <ol> <li>You don't control the data and thus can't properly escape the commas.</li> <li>The first three columns won't contain any comma.</strike></li> <li>The third column follows the syntax of a python dict.</li> <li>There is always one value in the list which is in the dict values.</li> </ol> <p>First, some imports</p> <pre><code>import ast import pandas as pd </code></pre> <p><strike>We'll just split the rows by commas as we don't need to deal with any sort of CSV escaping (assumptions #1 and #2).</p> <pre><code>rows = (line.split(",", 3) for line in the_data.splitlines() if line.strip() != "") fixed_columns = pd.DataFrame.from_records(rows, columns=["Company", "Date", "Value", "Cars_str"]) </code></pre> <p></strike></p> <pre><code>fixed_columns = pd.read_csv(..., names=["Company", "Date", "Value", "Cars_str"]) </code></pre> <p>The first three columns are fixed and we leave them as they are. The last column we can parse with <code>ast.literal_eval</code> because it's a <code>dict</code> (assumption #3). This is IMO more readable and more flexible if the format changes than regex. Also you'll detect the format change earlier.</p> <pre><code>cars = fixed_columns["Cars_str"].apply(ast.literal_eval) del fixed_columns["Cars_str"] </code></pre> <p>And this part answers rather <a href="http://stackoverflow.com/questions/39935744/wrangling-a-data-frame-in-pandas-python">your other question</a>.</p> <p>We prepare functions to process the keys and values of the dict so they fail if our assumptions about content of the dict fail.</p> <pre><code>def get_single_item(list_that_always_has_single_item): v, = list_that_always_has_single_item return v def extract_car_name(car_str): assert car_str.startswith("//"), car_str return car_str[2:] </code></pre> <p>We apply the functions and construct <code>pd.Series</code> which allow us to...</p> <pre><code>dynamic_columns = cars.apply( lambda x: pd.Series({ extract_car_name(k): get_single_item(v) for k, v in x.items() })) </code></pre> <p>...add the columns to the dataframe</p> <pre><code>result = pd.concat([fixed_columns, dynamic_columns], axis=1) result </code></pre> <p>Finally, we get the table:</p> <pre><code> Company Date Value BlackCar BlueCar NPO-GreenCar PinkCar \ 0 ABC 2016-6-9 0:00 95 NaN 16.0 NaN NaN 1 ABC 2016-6-10 0:00 0 NaN 90.0 NaN NaN 2 ABC 2016-6-11 0:00 0 NaN 31.0 NaN NaN 3 ABC 2016-6-12 0:00 0 NaN 8888.0 NaN NaN 4 ABC 2016-6-13 0:00 0 NaN 4.0 NaN NaN 5 DEF 2016-6-16 0:00 0 15.0 NaN 0.0 4.0 6 DEF 2016-6-17 0:00 0 15.0 NaN 0.0 4.0 7 DEF 2016-6-18 0:00 0 15.0 NaN 0.0 4.0 8 DEF 2016-6-19 0:00 0 15.0 NaN 0.0 4.0 9 DEF 2016-6-20 0:00 0 15.0 NaN 0.0 4.0 PurpleCar WhiteCar-XYZ YellowCar 0 115.0 0.0 403.0 1 219.0 0.0 381.0 2 817.0 0.0 21.0 3 80.0 0.0 2011.0 4 32.0 0.0 15.0 5 32.0 NaN NaN 6 32.0 NaN NaN 7 32.0 NaN NaN 8 32.0 NaN NaN 9 32.0 NaN NaN </code></pre>
1
2016-10-08T19:49:58Z
[ "python", "regex", "pandas" ]