title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Adding Macros to Python
15,669,921
19
2013-03-27T21:31:52Z
15,669,966
12
2013-03-27T21:34:33Z
[ "python", "macropy" ]
I would like to invoke the following code **in-situ** wherever I refer to `MY_MACRO` in my code below. ``` # MY_MACRO frameinfo = getframeinfo(currentframe()) msg = 'We are on file ' + frameinfo.filename + ' and line ' + str(frameinfo.lineno) # Assumes access to namespace and the variables in which `MY_MACRO` is call...
How about a function you can call? This function accesses the caller's frame, and rather than using `locals()`, uses `frame.f_locals` to get the caller's namespace. ``` def my_function(): frame = currentframe().f_back msg = 'We are on file {0.f_code.co_filename} and line {0.f_lineno}'.format(frame) current...
Adding Macros to Python
15,669,921
19
2013-03-27T21:31:52Z
16,493,664
20
2013-05-11T04:10:38Z
[ "python", "macropy" ]
I would like to invoke the following code **in-situ** wherever I refer to `MY_MACRO` in my code below. ``` # MY_MACRO frameinfo = getframeinfo(currentframe()) msg = 'We are on file ' + frameinfo.filename + ' and line ' + str(frameinfo.lineno) # Assumes access to namespace and the variables in which `MY_MACRO` is call...
[MacroPy](https://github.com/lihaoyi/macropy) is a project of mine which brings syntactic macros to Python. The project is only 3 weeks old, but if you look at the link, you'll see we have a pretty cool collection of demos, and the functionality you want can definitely be implemented using it. On the other hand, pytho...
Speed up solving a triangular linear system with numpy?
15,670,094
9
2013-03-27T21:42:39Z
16,968,250
9
2013-06-06T17:17:13Z
[ "python", "numpy", "scipy", "linear-algebra" ]
I have a square matrix S (160 x 160), and a huge matrix X (160 x 250000). Both are dense numpy arrays. My goal: find Q such that Q = inv(chol(S)) \* X, where chol(S) is the lower cholesky factorization of S. Naturally, a simple solution is ``` cholS = scipy.linalg.cholesky( S, lower=True) scipy.linalg.solve( cholS, ...
TL;DR: Don't use numpy's or scipy's `solve` when you have a triangular system, just use `scipy.linalg.solve_triangular` with at least the `check_finite=False` keyword argument for fast and non-destructive solutions. --- I found this thread after stumbling across some discrepancies between `numpy.linalg.solve` and `sc...
Comparison of Python modes for Emacs
15,670,505
38
2013-03-27T22:10:59Z
15,672,445
21
2013-03-28T01:01:02Z
[ "python", "emacs" ]
So I have Emacs 24.3 and with it comes a quite recent `python.el` file providing a Python mode for editing. But I keep reading that there is a `python-mode.el` on [Launchpad](http://bazaar.launchpad.net/~python-mode-devs/python-mode/python-mode/view/head:/python-mode.el), and comparing the two files it jumps out to me...
I was python-mode.el user once but quit using it a year ago because I felt the way it was developed was not well organized. Here is a list from the note I took at that time. But I need to warn you that almost a year is passed since then so the situation may be changed. 1. Many copy & paste functions. 2. Many accidenta...
Prevent multiple form submissions in Django
15,671,335
2
2013-03-27T23:12:19Z
15,671,443
8
2013-03-27T23:23:01Z
[ "python", "django", "forms", "hash" ]
I'm looking for a generic way to prevent multiple form submissions. I found this [approach](https://gist.github.com/saketkc/1439694) which looks promising. Whereas I do not want to include this snippet in all of my views. Its probably easier to do this with a request processor or a middleware. Any best practice recomm...
Client side, start with JavaScript. You can never trust the client, but its a start. i.e. ``` onclick="this.disabled=true,this.form.submit(); ``` Server side you 'could' insert something into a database i.e. a checksum. If its a records you are insert into a database use `model.objects.get_or_create()` to force the ...
Is it possible for a unit test to assert that a method calls sys.exit()
15,672,151
40
2013-03-28T00:29:34Z
15,672,165
59
2013-03-28T00:30:49Z
[ "python", "unit-testing" ]
I have a python 2.7 method that sometimes calls ``` sys.exit(1) ``` Is it possible to make a unit test that verifies this line of code is called when the right conditions are met?
Yes. `sys.exit` raises `SystemExit`, so you can check it with [`assertRaises`](http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises): ``` with self.assertRaises(SystemExit): your_method() ``` Instances of `SystemExit` have an attribute `code` which is set to the proposed exit status, and ...
Displaying a tree in ASCII
15,675,261
7
2013-03-28T06:05:11Z
17,462,524
10
2013-07-04T05:32:47Z
[ "python", "tree" ]
As a time-pass activity, I decided to implement a [Tree](http://en.wikipedia.org/wiki/Tree_%28data_structure%29)(like) structure in python. I implemented a `Node` class (which alone serves the purpose here) like so: ``` class Node: def __init__(self, name, parent, *data): self.name = name self.pa...
Here's a solution that covers most of what you're looking for. Like any tree algorithm, recurse down the children of the tree, and combine results at each node. Here's the trick: `display()` returns a rectangle of text, for example: ``` aaaaaa aaaaaa aaaaaa ``` Most of the rectangle will be whitespace. Returning onl...
AppEngine Google Cloud Endpoint - discovery not found
15,675,587
4
2013-03-28T06:30:52Z
15,683,236
8
2013-03-28T13:31:06Z
[ "python", "google-app-engine", "google-cloud-endpoints" ]
I am quite new to Python and Google AppEngine, but have had around 7 years of programming experience. I am also new to StackOverflow. I've been trying to set up a simple Google Cloud Endpoint API for my personal project, and have finished and uploaded the finished app to Google App Engine. Here are my Endpoint API se...
See the documentation here: <https://developers.google.com/appengine/docs/python/endpoints/api_server> You need to do the following: Change your app.yaml to: ``` handlers: - url: /favicon\.ico static_files: favicon.ico upload: favicon\.ico - url: /_ah/spi/.* script: services.application - url: .* script: m...
django - get the latest record with filter
15,675,672
32
2013-03-28T06:37:21Z
15,675,846
31
2013-03-28T06:48:39Z
[ "python", "django", "django-models" ]
i am trying to get the latest django model object but cannot seem to succeed. neither ``` obj= Model.objects.filter(testfield=12).latest() ``` nor ``` obj= Model.objects.latest().filter(testfield=12) ``` is working. please help.
``` obj= Model.objects.filter(testfield=12).order_by('-id')[0] ```
django - get the latest record with filter
15,675,672
32
2013-03-28T06:37:21Z
15,675,948
9
2013-03-28T06:55:42Z
[ "python", "django", "django-models" ]
i am trying to get the latest django model object but cannot seem to succeed. neither ``` obj= Model.objects.filter(testfield=12).latest() ``` nor ``` obj= Model.objects.latest().filter(testfield=12) ``` is working. please help.
`latest` is really designed to work with date fields (it probably does work with other total-ordered types too, but not sure). And the only way you can use it without specifying the field name is by setting the `get_latest_by` meta attribute, as mentioned [here](https://docs.djangoproject.com/en/dev/ref/models/queryset...
django - get the latest record with filter
15,675,672
32
2013-03-28T06:37:21Z
21,978,418
35
2014-02-24T03:31:40Z
[ "python", "django", "django-models" ]
i am trying to get the latest django model object but cannot seem to succeed. neither ``` obj= Model.objects.filter(testfield=12).latest() ``` nor ``` obj= Model.objects.latest().filter(testfield=12) ``` is working. please help.
See the docs from django: <https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest> You need to specify a field in latest(). eg. ``` obj= Model.objects.filter(testfield=12).latest('testfield') ``` Or if your model’s Meta specifies get\_latest\_by, you can leave off the `field_name` argument to `earliest...
Merge dictionaries and add values
15,677,693
4
2013-03-28T08:58:27Z
15,677,881
8
2013-03-28T09:09:17Z
[ "python" ]
I have several dictionaries which I'd like to combine such that if a key is in multiple dictionaries the values are added together. For example: ``` d1 = {1: 10, 2: 20, 3: 30} d2 = {1: 1, 2: 2, 3: 3} d3 = {0: 0} merged = {1: 11, 2: 22, 3: 33, 0: 0} ``` What is the best way to do this in Python? I was looking at defa...
using a `defaultdict`: ``` >>> d = defaultdict(int) >>> for di in [d1,d2,d3]: ... for k,v in di.items(): ... d[k] += v ... >>> dict(d) {0: 0, 1: 11, 2: 22, 3: 33} >>> ```
Homebrew + Python on mac os x 10.8: Fatal Python error: PyThreadState_Get: no current thread importing mapnik
15,678,153
24
2013-03-28T09:23:58Z
15,735,588
10
2013-03-31T23:05:17Z
[ "python", "module", "homebrew", "mapnik" ]
I have 2 pythons on my mac (10.8.3): The default, and 2.7 version from homebrew. So far, I could install modules and use them with my brew python. I installed mapnik with `brew install mapnik` (mapnik-2.1.0) and it compiled correctly. But, if I open python and enter `import mapnik`, the following error comes and pytho...
It looks like you are running the homebrew python but either boost python or mapnik's python bindings ended up linking against the system python provided by apple. If a full clean and reinstall of boost and Mapnik does not fix this then I recommend stopping by #mapnik irc on freenode for help debugging. Generally to fi...
Using multiple colors in matplotlib plot
15,678,373
10
2013-03-28T09:35:49Z
15,679,678
12
2013-03-28T10:42:00Z
[ "python", "colors", "matplotlib", "plot" ]
I have a numpy array of 2D data points (x,y), which are classified into three categories (0,1,2). ``` a = array([[ 1, 2, 3, 4, 5, 6, 7, 8 ], [ 9, 8, 7, 6, 5, 4, 3, 2 ]]) class = array([0, 2, 1, 1, 1, 2, 0, 0]) ``` My question is if I can plot these points with multiple colors. I would like to do something...
I assume you want to plot distinct points. In that case, if you define a numpy array: ``` colormap = np.array(['r', 'g', 'b']) ``` then you can generate the array of colors with `colormap[categories]`: ``` In [18]: colormap[categories] Out[18]: array(['r', 'b', 'g', 'g', 'g', 'b', 'r', 'r'], dtype='|S1') ```...
Please explain these Python Fetch types
15,679,782
5
2013-03-28T10:47:11Z
15,679,995
14
2013-03-28T10:57:04Z
[ "python", "openerp" ]
What is the difference between these fetching.? please give me a examples for reference site to get clear idea.still i'm confuse with it ``` res = cr.dictfetchall() res2 = cr.dictfetchone() res3 = cr.fetchall() res4 = cr.fetchone() ``` cr is the current row, from the database cursor (OPENERP 7 ) ex : ``` def _ma...
`cr.dictfetchall()` will give you all the matching records in the form of \*\* list of dictionary\*\* containing **key, value**. `cr.dictfetchone()` works same way as `cr.dictfetchall()` except it returns only single record. `cr.fetchall()` will give you all the matching records in the form of **list of tupple**. `c...
numpy: 1D array with various shape
15,680,593
10
2013-03-28T11:28:05Z
15,680,781
10
2013-03-28T11:38:22Z
[ "python", "arrays", "numpy" ]
I try to understand how to handle 1D array (vector in linear algebra) with numpy. In the following example, I generate two numpy.array a and b: ``` >>> import numpy as np >>> a = np.array([1,2,3]) >>> b = np.array([[1],[2],[3]]).reshape(1,3) >>> a.shape (3,) >>> b.shape (1, 3) ``` For me, a and b have the same shape ...
Notice you are not only working with 1D arrays: ``` In [6]: a.ndim Out[6]: 1 In [7]: b.ndim Out[7]: 2 ``` So, `b` is a 2D array. You also see this in the output of `b.shape`: (1,3) indicates two dimensions as (3,) is one dimension. The behaviour of `np.dot` is different for 1D and 2D arrays (from the [docs](http://...
Evaluation order of dictionary literals
15,681,054
5
2013-03-28T11:51:58Z
15,681,329
10
2013-03-28T12:04:39Z
[ "python", "dictionary" ]
``` def key(): print 'key' def val(): print 'val' {key() : val()} ``` prints `val, key`, i.e. the value is evaluated first. Is this behaviour * consistent across python versions and implementations? * documented anywhere? (<http://docs.python.org/2/reference/expressions.html#dictionary-displays> says nothing)
This section of the reference manual documents the order, but claims it is different than what you are seeing: <http://docs.python.org/2/reference/expressions.html#evaluation-order> > In the following lines, expressions will be evaluated in the arithmetic order of their suffixes: ``` expr1, expr2, expr3, expr4 (expr1...
sqlite - works with file, dies with :memory:
15,681,387
4
2013-03-28T12:07:11Z
15,681,692
9
2013-03-28T12:21:47Z
[ "python", "sqlite", "sqlalchemy" ]
My script fails tests when working with [SQLite](http://en.wikipedia.org/wiki/SQLite) base (via [sqlalchemy](http://www.sqlalchemy.org/)) created in `:memory:` and passes tests when working with a base created with physical file. The script is multi-threaded. I know it is not the best idea to use SQLite with multiple ...
You cannot create multiple connections to an in-memory database. Instead, a new connection to `:memory:` creates a *new* database. From the [SQLite documentation](http://www.sqlite.org/inmemorydb.html): > Every :memory: database is distinct from every other. So, opening two database connections each with the filename...
How to add custom button to a QMessageBox in PyQt4
15,682,665
6
2013-03-28T13:07:29Z
15,683,962
12
2013-03-28T14:06:24Z
[ "python", "pyqt" ]
I am coding a application which needs a custom buttons in QMessageBox. i managed to create an example in QT designer which is given below. ![enter image description here](http://i.stack.imgur.com/QrLJ6.jpg) i wanted to do this in a QMessageBox. I am using python 2.6.4 and PyQt4. please, can any one help.
Here is an example of building a custom message box from the ground up. ``` import sys from PyQt4 import QtCore, QtGui class Example(QtGui.QDialog): def __init__(self, parent=None): super(Example, self).__init__(parent) msgBox = QtGui.QMessageBox() msgBox.setText('What to do?') m...
Iterating through a pandas dataframe
15,683,588
2
2013-03-28T13:48:22Z
15,688,840
7
2013-03-28T17:54:13Z
[ "python", "pandas" ]
I have a pandas dataframe where one column represents if the location value in another column changed in the row below it. As an example, ``` 2013-02-05 19:45:00 (39.94, -86.159) True 2013-02-05 19:50:00 (39.94, -86.159) True 2013-02-05 19:55:00 (39.94, -86.159) False 2013-02-05 20:00:00 (39.777, -85...
Here's another take ``` df['group'] = (df.condition == False).astype('int').cumsum().shift(1).fillna(0) df date long lat condition group 2/5/2013 19:45:00 39.940 -86.159 True 0 2/5/2013 19:50:00 39.940 -86.159 True 0 2/5/2013 19:55:00 39.940 -86.159 False 0 2/5/201...
Python: Implementation of shallow and deep copy constructors
15,684,881
7
2013-03-28T14:48:01Z
15,685,014
17
2013-03-28T14:52:44Z
[ "python", "copy-constructor", "deep-copy" ]
It is in most of the situations easy to implement copy constructors (or overloaded assignment operator) in C++ since there is a concept of pointers. However, I'm quite confused about how to implement shallow and deep copy in Python. I know that there are special commands in one of the libraries but they don't work on ...
The python [`copy` module](http://docs.python.org/2/library/copy.html) can reuse the [`pickle` module](http://docs.python.org/2/library/pickle.html#module-pickle) interface for letting classes customize copy behaviour. The default for instances of custom classes is to create a new, empty class, swap out the `__class__...
Rudimentary Computer Vision Techniques for Python Bot.
15,685,894
2
2013-03-28T15:31:00Z
15,707,978
7
2013-03-29T17:07:45Z
[ "python", "opencv", "computer-vision", "bots" ]
After completion several chapters in computer vision books I decided to apply those methods to create some primitive bot for a game. I chose [Fling](http://www.miniclip.com/games/fling/en/) that has almost no dynamics and all I needed to do was to find balls. Balls may have 5 different colors and also they can be direc...
The balls seem pretty distinct in terms of colour. The problems you initially described seem to be related to some of the finer, random detail present in the image - especially in the background and in the different shading/poses of the ball. On this basis, I would say you could simplify the task significantly by appl...
Why do "Not a Number" values equal True when cast as boolean in Python/Numpy?
15,686,318
11
2013-03-28T15:49:03Z
15,686,477
11
2013-03-28T15:55:52Z
[ "python", "math", "numpy" ]
When casting a NumPy Not-a-Number value as a boolean, it becomes True, e.g. as follows. ``` >>> import numpy as np >>> bool(np.nan) True ``` This is the exact opposite to what I would intuitively expect. Is there a sound principle underlying this behaviour? (I suspect there might be as the same behaviour seems to oc...
This is in no way NumPy-specific, but is consistent with how Python treats NaNs: ``` In [1]: bool(float('nan')) Out[1]: True ``` The rules are spelled out in the [documentation](http://docs.python.org/2/library/stdtypes.html#truth-value-testing). I think it could be reasonably argued that the truth value of NaN shou...
Python print isn't using __repr__, __unicode__ or __str__ for unicode subclass?
15,687,676
10
2013-03-28T16:51:51Z
15,687,898
10
2013-03-28T17:05:08Z
[ "python", "class", "unicode", "subclass", "derived-class" ]
Python print isn't using `__repr__`, `__unicode__` or `__str__` for my unicode subclass when printing. Any clues as to what I am doing wrong? Here is my code: Using Python 2.5.2 (r252:60911, Oct 13 2009, 14:11:59) ``` >>> class MyUni(unicode): ... def __repr__(self): ... return "__repr__" ... def __u...
The problem is that `print` doesn't respect `__str__` on `unicode` subclasses. From [`PyFile_WriteObject`](http://hg.python.org/cpython/file/2145593d108d/Objects/fileobject.c), used by `print`: ``` int PyFile_WriteObject(PyObject *v, PyObject *f, int flags) { ... if ((flags & Py_PRINT_RAW) && PyUnicode_Ch...
Django project on 80 port?
15,689,641
2
2013-03-28T18:35:16Z
15,689,718
7
2013-03-28T18:39:57Z
[ "python", "django", "ubuntu-server" ]
Ι have developed a Django project and uploaded it to a cloud VΜ. Currently i have access to it through 8080 port. ``` python manage.py runserver 0.0.0.0:8080 ``` If i enter the url without the 8080 port, it shows the "it works" page. How can i set my Django project to run by default on 80 port? I am using Ubuntu 1...
As [docs say](https://docs.djangoproject.com/en/dev/ref/django-admin/#runserver-port-or-address-port), `runserver` isn't meant as a deployment server. It also mentions that you probably can't start it on port 80 unless you run it as root.
python: datetime tzinfo time zone names documentation
15,692,906
12
2013-03-28T21:59:24Z
15,692,958
18
2013-03-28T22:02:24Z
[ "python", "datetime", "timezone" ]
I have a date that I build: ``` from datetime import datetime from datetime import tzinfo test = '2013-03-27 23:05' test2 = datetime.strptime(test,'%Y-%m-%d %H:%M') >>> test2 datetime.datetime(2013, 3, 27, 23, 5) >>> test2.replace(tzinfo=EST) Traceback (most recent call last): File "<stdin>", line 1, in <module> Na...
The standard library does not define any timezones -- at least not well (the toy example given in [the documentation](http://docs.python.org/2/library/datetime.html#tzinfo-objects) does not handle subtle problems like the ones [mentioned here](http://pytz.sourceforge.net/#problems-with-localtime)). For predefined timez...
Why does HTTP POST request body need to be JSON enconded in Python?
15,694,120
5
2013-03-28T23:45:29Z
15,696,705
11
2013-03-29T03:06:18Z
[ "python", "http", "python-requests" ]
I ran into this issue when playing around with an external API. I was sending my body data as a dictionary straight into the request and was getting 400 errors: ``` data = { "someParamRange": { "to": 1000, "from": 100 }, "anotherParamRange": { "to": True, "from": False } } ``` When I added ...
Apparently your API requires JSON-encoded and not form-encoded data. When you pass a `dict` in as the `data` parameter, the data is form-encoded. When you pass a string (like the result of `json.dumps`), the data is not form-encoded. Consider this quote from the requests documentation: > > Typically, you want to send...
Filter elements from the end of a list
15,695,915
3
2013-03-29T01:20:39Z
15,695,976
8
2013-03-29T01:28:37Z
[ "python", "list", "filter" ]
I have a data structure that looks like this: ``` [(1, 2), (2, 3), (4, 0), (5, 10), (6, 0), (7, 0)] ``` What is the best way to filter out only tuples at the end of the list where the second element is 0? The desired output is: ``` [(1, 2), (2, 3), (4, 0), (5, 10)] ```
This sounds to me like you want a '`rstrip()` for lists'. You can use `.pop()` with a while loop: ``` while somelist and somelist[-1][1] == 0: somelist.pop() ``` This alters the list *in place*. To create a copy, you'd have to first find a slice end-point, then slice up to that point for a quick copy: ``` end =...
Import Python Script Into Another?
15,696,461
18
2013-03-29T02:31:25Z
15,696,507
38
2013-03-29T02:37:33Z
[ "python", "python-2.7", "import" ]
I'm going through Zed Shaw's Learn Python The Hard Way and I'm on lesson 26. In this lesson we have to fix some code, and the code calls functions from another script. He says that we don't have to import them to pass the test, but I'm curious as to how we would do so. [Link to the lesson](http://learnpythonthehardway...
It depends on how the code in the first file is structured. If it's just a bunch of functions, like: ``` # first.py def foo(): print("foo") def bar(): print("bar") ``` Then you could import it and use the functions as follows: ``` # second.py import first first.foo() # prints "foo" first.bar() # prints "bar...
Import Python Script Into Another?
15,696,461
18
2013-03-29T02:31:25Z
25,764,162
11
2014-09-10T11:24:56Z
[ "python", "python-2.7", "import" ]
I'm going through Zed Shaw's Learn Python The Hard Way and I'm on lesson 26. In this lesson we have to fix some code, and the code calls functions from another script. He says that we don't have to import them to pass the test, but I'm curious as to how we would do so. [Link to the lesson](http://learnpythonthehardway...
It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named `__init__.py` in the same directory.
SSL throwing error 185090050 while authentication via Oauth
15,696,526
7
2013-03-29T02:39:37Z
19,028,821
7
2013-09-26T12:51:14Z
[ "python", "authentication", "ssl", "oauth-2.0", "adsense" ]
I am trying use Google's Oauth to connect to Google adsense and am getting this error. Any clues to fix it? Anyone has faced such a issue before in python? ``` Traceback (most recent call last): File "get_all_saved_reports.py", line 56, in <module> main(sys.argv) File "get_all_saved_reports.py", lin...
This issue is while loading the certificates files.If you run the program with root user this issue will be solved. Or you can check the permissions of the file :/usr/local/lib/python2.7/dist-packages/httplib2-0.8-py2.7.egg/httplib2/cacerts.txt, and provide the necessary permission to this file.
SSL throwing error 185090050 while authentication via Oauth
15,696,526
7
2013-03-29T02:39:37Z
19,145,997
29
2013-10-02T20:13:47Z
[ "python", "authentication", "ssl", "oauth-2.0", "adsense" ]
I am trying use Google's Oauth to connect to Google adsense and am getting this error. Any clues to fix it? Anyone has faced such a issue before in python? ``` Traceback (most recent call last): File "get_all_saved_reports.py", line 56, in <module> main(sys.argv) File "get_all_saved_reports.py", lin...
I was getting this exact x509 error in oauth2 (for Twitter API, not Google) with Python 2.7.5 and used Akshay Valsa's advice and changed the permissions on cacerts.txt with ``` chmod 644 /usr/local/lib/python2.7/dist-packages/httplib2-0.8-py2.7.egg/httplib2/cacerts.txt ``` That fixed the problem and I can now run my ...
selecting numbers from a list in python
15,697,041
3
2013-03-29T03:52:33Z
15,697,094
11
2013-03-29T03:57:36Z
[ "python", "list", "random" ]
I am working on a program that generates a single elimination tournament. so far my code looks like this ( i have just started) ``` amount = int(raw_input("How many teams are playing in this tournament? ")) teams = [] i = 0 while i<amount: teams.append(raw_input("please enter team name: ")) i= i+1 ``` now i...
Take a look at the [`random`](http://docs.python.org/library/random.html) module. ``` >>> import random >>> teams = ['One team', 'Another team', 'A third team'] >>> team1, team2 = random.sample(teams, 2) >>> print team1 'Another team' >>> print team2 'One team' ```
Binning frequency distribution in Python
15,697,350
4
2013-03-29T04:28:02Z
15,697,950
7
2013-03-29T05:37:49Z
[ "python", "numpy", "histogram" ]
I have data in the two lists *value* and *freq* like this: ``` value freq 1 2 2 1 3 3 6 2 7 3 8 3 .... ``` and I want the output to be ``` bin freq 1-3 6 4-6 2 7-9 6 ... ``` I can write few lines of code to do this. However, I am looking if there are builitin functions in standar...
``` import numpy as np values = [1,2,3,6,7,8] freqs = [2,1,3,2,3,3] hist, _ = np.histogram(values, bins=[1, 4, 7, 10], weights=freqs) print hist ``` output: ``` [6 2 6] ```
Converting string to raw bytes
15,701,860
2
2013-03-29T10:55:46Z
15,702,044
8
2013-03-29T11:08:00Z
[ "python", "arrays", "string", "byte" ]
I wrote a program that works with raw bytes (I don't know if this is the right name!) but the user will input the data as plain strings. How to convert them? I've tried wih a method but it returns a string with length 0! Here's the starting string: ``` 5A05705DC25CA15123C8E4750B80D0A9 ``` Here's the result that I ...
Use [`binascii.unhexlify()`](http://docs.python.org/2/library/binascii.html#binascii.unhexlify): ``` import binascii binary = binascii.unhexlify(text) ``` The same module has [`binascii.hexlify()`](http://docs.python.org/2/library/binascii.html#binascii.hexlify) too, to mirror the operation. Demo: ``` >>> import b...
QThread: Destroyed while thread is still running
15,702,782
7
2013-03-29T11:59:42Z
15,702,922
13
2013-03-29T12:08:20Z
[ "python", "pyqt", "qthread" ]
I'm having problem with QThreads in python. I want to change background color of label. But My application crash while starting. "QThread: Destroyed while thread is still running" ``` class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() ...
You're not storing a reference to the thread after it's been created, which means that it will be garbage collected (ie. destroyed) some time after the program leaves `MainWindow`s `__init__`. You need to store it at least as long as the thread is running, for example use `self.statusTh`: ``` self.statusTh = statusThr...
Routes with trailing slashes in Pyramid
15,705,399
4
2013-03-29T14:35:41Z
15,708,788
9
2013-03-29T18:00:11Z
[ "python", "url-routing", "pyramid" ]
Let's say I have a route '/foo/bar/baz'. I would also like to have another view corresponding to '/foo' or '/foo/'. But I don't want to systematically append trailing slashes for other routes, only for /foo and a few others (/buz but not /biz) From what I saw I cannot simply define two routes with the same route\_name...
Pyramid has a way for `HTTPNotFound` views to **automatically append a slash** and test the routes again for a match (the way Django's `APPEND_SLASH=True` works). Take a look at: **<http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/urldispatch.html#redirecting-to-slash-appended-routes>** As per this examp...
Python: drop root privileges for certain operations
15,705,439
9
2013-03-29T14:37:56Z
15,707,075
7
2013-03-29T16:16:06Z
[ "python", "linux", "root", "sudo", "privileges" ]
In my Python script, I perform a few operations that need root privileges. I also create and write to files that I don't want to be owned exclusively by root but by the user who is running my script. Usually, I run my script using `sudo`. Is there a way to do the above?
You can switch between uid's using `os.seteuid()`. This differs from `os.setuid()` in that you can go back to getting root privileges when you need them. For example, run the following as root: ``` import os open('file1', 'wc') # switch to userid 501 os.seteuid(501) open('file2', 'wc') # switch back to root os.set...
Python : Getting the Row which has the max value in groups using groupby
15,705,630
16
2013-03-29T14:48:13Z
15,705,958
41
2013-03-29T15:09:40Z
[ "python", "pandas" ]
I hope I can find help for my question. I am searching for a solution for the following problem: I have a dataFrame like: ``` Sp Mt Value count 0 MM1 S1 a **3** 1 MM1 S1 n 2 2 MM1 S3 cb 5 3 MM2 S3 mk **8** 4 MM2 S4 bg **10** 5 MM2 S4 dgd 1 6 MM4 S2 rd 2 7 ...
``` In [1]: df Out[1]: Sp Mt Value count 0 MM1 S1 a 3 1 MM1 S1 n 2 2 MM1 S3 cb 5 3 MM2 S3 mk 8 4 MM2 S4 bg 10 5 MM2 S4 dgd 1 6 MM4 S2 rd 2 7 MM4 S2 cb 2 8 MM4 S2 uyi 7 In [2]: df.groupby(['Mt'], sort=False)['count'].max() Ou...
Python : Getting the Row which has the max value in groups using groupby
15,705,630
16
2013-03-29T14:48:13Z
21,709,413
8
2014-02-11T17:54:50Z
[ "python", "pandas" ]
I hope I can find help for my question. I am searching for a solution for the following problem: I have a dataFrame like: ``` Sp Mt Value count 0 MM1 S1 a **3** 1 MM1 S1 n 2 2 MM1 S3 cb 5 3 MM2 S3 mk **8** 4 MM2 S4 bg **10** 5 MM2 S4 dgd 1 6 MM4 S2 rd 2 7 ...
Having tried the solution suggested by Zelazny on a relatively large DataFrame (~400k rows) I found it to be very slow. Here is an alternative that I found to run orders of magnitude faster on my data set. ``` df = pd.DataFrame({ 'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4', 'MM4'], 'mt' : ['...
How to compute "EMD" for 2 numpy arrays i.e "histogram" using opencv?
15,706,339
10
2013-03-29T15:31:57Z
15,883,221
15
2013-04-08T15:33:11Z
[ "python", "opencv", "numpy", "histogram", "earthdistance" ]
Since I'm new to opencv, I don't know how to use the [`cv.CalcEMD2`](http://docs.opencv.org/modules/imgproc/doc/histograms.html#emd) function with `numpy` arrays. I have two arrays: ``` a=[1,2,3,4,5] b=[1,2,3,4] ``` How can I transfer `numpy array` to `CVhistogram` and from `Cvhistogram` to the function parameter...
You have to define your arrays in terms of weights and coordinates. If you have two arrays a = [1,1,0,0,1] and b = [0,1,0,1] that represent one dimensional histograms, then the numpy arrays should look like this: ``` a = [[1 1] [1 2] [0 3] [0 4] [1 5]] b = [[0 1] [1 2] [0 3] [1 4]] ...
generator in Python generating prime numbers
15,706,911
3
2013-03-29T16:07:05Z
15,706,985
7
2013-03-29T16:10:54Z
[ "python", "generator", "primes" ]
I need to generate prime numbers using generator in Python. Here is my code: ``` def genPrimes(): yield 2 x=2 while True: x+=1 for p in genPrimes(): if (x%p)==0: break else: yield x ``` I have a RuntimeError: maximum recursion depth exceeded ...
`genPrimes()` unconditionally calls itself with exactly the same arguments. This leads to infinite recursion. Here is one way to do it using a (non-recursive) generator: ``` def gen_primes(): n = 2 primes = set() while True: for p in primes: if n % p == 0: break ...
Installing PyGame onto Mountain Lion OS
15,706,930
5
2013-03-29T16:08:11Z
15,707,642
7
2013-03-29T16:48:22Z
[ "python", "osx", "pygame", "osx-mountain-lion" ]
Okay, so I've completely given up. I've tried about a thousand different walkthroughs to solve my problem, on every website I can find, but I either get stuck and no one knows the answer, or they just don't work. So has anyone got an answer to installing PyGame onto Mountain Lion that they know 100% works and they ca...
Ok, I'm running OSX 10.8.3 (Python 2.7.3), and I got pygame (1.9.1) up and running in about 15 minutes. Here's what I did. I brewed my Python a long time ago, so I forget the steps there. I seem to remember editing some symbolic links in `\usr\local`. At any rate, I'll assume you can use google as well as I can to fig...
Get time of execution of a block of code in Python 2.7
15,707,056
23
2013-03-29T16:15:08Z
15,707,125
51
2013-03-29T16:19:00Z
[ "python", "python-2.7", "profiler" ]
I would like to measure the time elapsed to evaluate a block of code in a Python program, possibly separating between user cpu time, system cpu time and elapsed time. I know the `timeit` module, but I have many self-written functions and it is not very easy to pass them in the setup process. I would rather have somet...
To get the elapsed time in seconds, you can use [`timeit.default_timer()`](http://docs.python.org/2/library/timeit.html#timeit.default_timer): ``` import timeit start_time = timeit.default_timer() # code you want to evaluate elapsed = timeit.default_timer() - start_time ``` `timeit.default_timer()` is used instead of...
How to arrive at the unit matrix from numpy.dot(A, A_inv)
15,707,215
2
2013-03-29T16:24:36Z
15,707,273
8
2013-03-29T16:28:02Z
[ "python", "numpy", "floating-point", "linear-algebra", "linear" ]
I prepare a matrix of random numbers, calculate its inverse and matrix multiply it with the original matrix. This, in theory, gives the unit matrix. How can I let `numpy` do that for me? ``` import numpy A = numpy.zeros((100,100)) E = numpy.zeros((100,100)) size = 100 for i in range(size): for j in range(size):...
While getting `True` would be didactically appealing, it would also be divorced from the realities of floating-point computations. When dealing with the floating point, one necessarily has to be prepared not only for inexact results, but for all manner of other numerical issues that arise. I highly recommend reading ...
python "import datetime" v.s. "from datetime import datetime"
15,707,532
11
2013-03-29T16:42:23Z
15,707,574
11
2013-03-29T16:44:10Z
[ "python", "datetime", "attributeerror" ]
I have a script that needs to execute the following at different lines in the script: ``` today_date = datetime.date.today() date_time = datetime.strp(date_time_string, '%Y-%m-%d %H:%M') ``` In my import statements I have the following: ``` from datetime import datetime import datetime ``` I get the following error...
You cannot use both statements; the `datetime` **module** contains a `datetime` **type**. The local name `datetime` in your own module can only refer to one or the other. Use *only* `import datetime`, then make sure that you always use `datetime.datetime` to refer to the contained type: ``` import datetime today_dat...
python "import datetime" v.s. "from datetime import datetime"
15,707,532
11
2013-03-29T16:42:23Z
15,707,648
25
2013-03-29T16:48:57Z
[ "python", "datetime", "attributeerror" ]
I have a script that needs to execute the following at different lines in the script: ``` today_date = datetime.date.today() date_time = datetime.strp(date_time_string, '%Y-%m-%d %H:%M') ``` In my import statements I have the following: ``` from datetime import datetime import datetime ``` I get the following error...
Your trouble is that you have some code that is expecting `datetime` to be a reference to the `datetime` *module* and other code that is expecting `datetime` to be a reference to the `datetime` *class.* Obviously, it can't be both. When you do: ``` from datetime import datetime import datetime ``` You are first sett...
Django: Lookup by length of text field
15,708,416
8
2013-03-29T17:35:41Z
15,708,877
12
2013-03-29T18:06:22Z
[ "python", "sql", "django" ]
I have a model with a text field on it. I want to do a lookup that will return all the items that have a string with a length of 7 or more in that field. Possible? How about a lookup for all objects in which that field isn't `''`?
I think regex lookup can help you: ``` ModelWithTextField.objects.filter(text_field__iregex=r'^.{7,}$') ``` or you can always perform raw SQL queries on Django model: ``` ModelWithTextField.objects.raw('SELECT * FROM model_with_text_field WHERE LEN_FUNC_NAME(text_field) > 7') ``` where len\_func\_name is the name o...
How can I handle an alert with GhostDriver via Python?
15,708,518
6
2013-03-29T17:42:27Z
15,838,919
10
2013-04-05T16:26:38Z
[ "javascript", "python", "selenium", "webdriver", "ghostdriver" ]
**Problem:** The GhostDriver API does not yet support alert handling. There is an acceptable workaround for the time being, which is to inject your own javascript into the page that will handle the alert and store it's text for you. I'm having trouble using this workaround via the python webdriver bindings. It might b...
A simple solution is to rewrite the window.alert method to output the argument to a global variable. Define the js injection variable with your override function: ``` js = """ window.alert = function(message) { lastAlert = message; } """ ``` And then just pass the js variable through the execute\_script call in pyth...
Python package dependency tree
15,708,723
19
2013-03-29T17:56:20Z
15,708,744
16
2013-03-29T17:57:28Z
[ "python", "dependency-management", "pypi" ]
I would like to analyze the dependency tree of Python packages. How can I obtain this data? Things I already know 1. `setup.py` sometimes contains a `requires` field that lists package dependencies 2. PyPi is an online repository of Python packages 3. PyPi has an API Things that I don't know 1. Very few projects (a...
You should be looking at the `install_requires` field *instead*, see [New and changed `setup` keywords](http://pythonhosted.org/setuptools/setuptools.html#new-and-changed-setup-keywords). `requires` is deemed too vague a field to rely on for dependency installation. In addition, there are `setup_requires` and `test_re...
Python 3 bytes formatting
15,710,515
14
2013-03-29T19:54:47Z
22,701,750
10
2014-03-28T00:06:29Z
[ "python", "python-3.x", "string-formatting" ]
In Python 3, one can format a string like: ``` "{0}, {1}, {2}".format(1, 2, 3) ``` But how to format bytes? ``` b"{0}, {1}, {2}".format(1, 2, 3) ``` raises `AttributeError: 'bytes' object has no attribute 'format'`. If there is no `format` method for bytes, how to do the formatting or "rewriting" of bytes?
And as of 3.5 `%` formatting will work for `bytes`, too! <https://mail.python.org/pipermail/python-dev/2014-March/133621.html>
Converting dict to OrderedDict
15,711,755
38
2013-03-29T21:35:00Z
15,711,843
76
2013-03-29T21:40:59Z
[ "python", "ordereddictionary" ]
I am having some trouble using the `collections.OrderedDict` class. I am using Python 2.7 on Raspbian, the Debian distro for Raspberry Pi. I am trying to print two dictionaries in order for comparison (side-by-side) for a text-adventure. The order is essential to compare accurately. No matter what I try the dictionarie...
You are creating a dictionary *first*, then passing that dictionary to an `OrderedDict`. By the time you do that, the ordering is no longer going to be correct. `dict` is inherently not ordered. Pass in a list of tuples instead: ``` ship = (("NAME", "Albatross"), ("HP", 50), ("BLASTERS",13), (...
Python regular expressions acting strangely
15,713,712
3
2013-03-30T00:57:59Z
15,713,736
9
2013-03-30T01:00:57Z
[ "python", "regex" ]
``` url = "http://www.domain.com/7464535" match = re.search(r'\d*',url) match.group(0) ``` returns '' <----- empty string but ``` url = "http://www.domain.com/7464535" match = re.search(r'\d+',url) match.group(0) ``` returns '7464535' I thought '+' was supposed to be 1 or more and '\*' was 0 or more correct? And R...
You are correct about the meanings of `+` and `*`. So `\d*` will match zero or more digits — and that's exactly what it's doing. Starting at the beginning of the string, it matches zero digits, and then it's done. It successfully matched zero or more digits. `*` is greedy, but that only means that it will match as m...
Remove the last N elements of a list
15,715,912
9
2013-03-30T06:57:20Z
15,715,924
27
2013-03-30T06:59:12Z
[ "python", "list" ]
Is there a a better way to remove the last N elements of a list. ``` for i in range(0,n): list.pop( ) ```
``` >>> L = [1,2,3, 4, 5] >>> n=2 >>> del L[-n:] >>> L [1, 2, 3] ```
Remove the last N elements of a list
15,715,912
9
2013-03-30T06:57:20Z
15,715,929
9
2013-03-30T06:59:38Z
[ "python", "list" ]
Is there a a better way to remove the last N elements of a list. ``` for i in range(0,n): list.pop( ) ```
if you wish to remove the last n elements, in other words, keep first len - n elements: ``` lst = lst[:n-1] ``` Note: This is not an in memory operation. It would create a copy.
Check if directory is symlink?
15,718,006
3
2013-03-30T11:26:37Z
15,718,056
11
2013-03-30T11:33:40Z
[ "python", "python-2.7" ]
In `os` there's a function `os.path.islink(PATH)` which checks if `PATH` is symlink. But if fails when PATH is a symlink to some directory. Instead -- python thinks it is directory (`os.path.isdir(PATH)`). So how do I check if a dir is link? **Edit**: Here's what `bash` thinks: ``` ~/scl/bkbkshit/Teaching: file 2_-_...
This happens because you put a slash at the end of the filename. ``` os.path.islink("2_-_Classical_Mechanics_(seminars)/") ^ ``` The trailing slash causes the OS to follow the link, so that the result is the target directory which is not a link. If you remove the slas...
Overload () operator in Python
15,719,172
18
2013-03-30T13:39:54Z
15,719,243
22
2013-03-30T13:49:02Z
[ "python", "operator-overloading" ]
I am trying to learn currying in Python for my class and I have to overload the () operator for it. However, I do not understand how can I can go about overloading the () operator. Can you explain the logic behind overloading the parentheses? Should I overload first ( and then ) or can I do any of these? Also, is there...
You can make an object callable by implementing the `__call__` method: ``` class FunctionLike(object): def __call__(self, a): print "I got called with %r!" % (a,) fn = FunctionLike() fn(10) # --> I got called with 10! ```
Python django: How to call selenium.set_speed() with django LiveServerTestCase
15,719,885
7
2013-03-30T14:57:15Z
15,760,068
7
2013-04-02T09:03:19Z
[ "python", "django", "binding", "selenium", "webdriver" ]
To run my functional tests i use `LiveServerTestCase`. I want to call `set_speed` (and other methods, `set_speed` is just an example) that aren't in the webdriver, but are in the selenium object. <http://selenium.googlecode.com/git/docs/api/py/selenium/selenium.selenium.html#module-selenium.selenium> my subclass of ...
You don't. Setting the speed in WebDriver is not possible and the reason for this is that you generally shouldn't need to, and the 'waiting' is now done at a different level. Before it was possible to tell Selenium, don't run this at normal speed, run it at a slower speed to allow more things to be available on page l...
pickle.load() raising EOFError in Windows
15,719,930
12
2013-03-30T15:01:39Z
15,719,966
24
2013-03-30T15:04:36Z
[ "python", "windows", "file-io", "newline", "pickle" ]
This is how the code is ``` with open(pickle_f, 'r') as fhand: obj = pickle.load(fhand) ``` This works fine on Linux systems but not on Windows. Its showing EOFError. I have to use `rb` mode to make it work on Windows.. now this isn't working on Linux. Why this is happening, and how to fix it?
Always use `b` mode when reading and writing pickles (`open(f, 'wb')` for writing, `open(f, 'rb')` for reading). To "fix" the file you already have, convert its newlines using `dos2unix`.
python: Two modules and classes with the same name under different packages
15,720,593
12
2013-03-30T16:06:31Z
15,720,621
17
2013-03-30T16:08:25Z
[ "python", "python-3.x", "package", "python-import" ]
I have started to learn python and writing a practice app. The directory structure looks like ``` src | --ShutterDeck | --Helper | --User.py -> class User --Controller | --User.py -> class User ``` The `src` directory is in `PYTHONPATH`. In a different file, lets say `main.py...
You want to import the `User` modules in the package `__init__.py` files to make them available as attributes. So in both `Helper/__init_.py` and `Controller/__init__.py` add: ``` from . import User ``` This makes the module an attribute of the package and you can now refer to it as such. Alternatively, you'd have ...
Can two processes access in-memory (:memory:) sqlite database concurrently?
15,720,700
5
2013-03-30T16:16:39Z
15,720,872
10
2013-03-30T16:35:45Z
[ "python", "sqlite" ]
Is it possible to access database in one process, created in another? I tried: **IDLE #1** ``` import sqlite3 conn = sqlite3.connect(':memory:') c = conn.cursor() c.execute("create table test(testcolumn)") c.execute("insert into test values('helloooo')") conn.commit() conn.close() ``` **IDLE #2** ``` import sqlite3...
No, they cannot ever access the same in-memory database. Instead, a new connection to `:memory:` *always* creates a *new* database. From the [SQLite documentation](http://www.sqlite.org/inmemorydb.html): > Every :memory: database is distinct from every other. So, opening two database connections each with the filenam...
What's the error of numpy.polyfit?
15,721,053
8
2013-03-30T16:55:34Z
15,721,453
8
2013-03-30T17:37:57Z
[ "python", "numpy" ]
I want to use numpy.polyfit for physical calculations, therefore I need the magnitude of the error.
If you specify `full=True` in your call to [`polyfit`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html), it will include extra information: ``` >>> x = np.arange(100) >>> y = x**2 + 3*x + 5 + np.random.rand(100) >>> np.polyfit(x, y, 2) array([ 0.99995888, 3.00221219, 5.56776641]) >>> np.polyfi...
What's the error of numpy.polyfit?
15,721,053
8
2013-03-30T16:55:34Z
15,721,508
10
2013-03-30T17:43:21Z
[ "python", "numpy" ]
I want to use numpy.polyfit for physical calculations, therefore I need the magnitude of the error.
As you can see in the [documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html): ``` Returns ------- p : ndarray, shape (M,) or (M, K) Polynomial coefficients, highest power first. If `y` was 2-D, the coefficients for `k`-th data set are in ``p[:,k]``. residuals, rank, singular_v...
Preserve Python tuples with JSON
15,721,363
15
2013-03-30T17:28:56Z
15,721,401
11
2013-03-30T17:32:04Z
[ "python", "json", "tuples" ]
I'm still a little new to this, so I might not know all the conventional terms for things: Is it possible to preserve Python tuples when encoding with JSON? Right now `json.loads(json.dumps(tuple))` gives me a list back. I don't want to convert my tuples to lists, but I want to use JSON. So, are there options? The re...
Nope, it's not possible. There is no concept of a tuple in the JSON format (see [here](http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example) for a concise breakdown of what types exist in JSON). Python's `json` module converts Python tuples to JSON lists because that's the closest thing in JSON to a tuple...
Preserve Python tuples with JSON
15,721,363
15
2013-03-30T17:28:56Z
15,721,641
15
2013-03-30T17:58:24Z
[ "python", "json", "tuples" ]
I'm still a little new to this, so I might not know all the conventional terms for things: Is it possible to preserve Python tuples when encoding with JSON? Right now `json.loads(json.dumps(tuple))` gives me a list back. I don't want to convert my tuples to lists, but I want to use JSON. So, are there options? The re...
You can write a highly-specialzed encoder and a decoder hook: ``` import json class MultiDimensionalArrayEncoder(json.JSONEncoder): def encode(self, obj): def hint_tuples(item): if isinstance(item, tuple): return {'__tuple__': True, 'items': item} if isinstance(item...
Update and render a value from Flask periodically
15,721,679
12
2013-03-30T18:02:01Z
25,564,098
13
2014-08-29T08:05:14Z
[ "javascript", "python", "flask", "jinja2" ]
I want to display my CPU usage dynamically. I don't want to reload the page to see a new value. I know how to get the CPU usage in Python. Right now I render a template with the value. How can I continually update a page with a value from Flask? ``` @app.route('/show_cpu') def show_cpu(): cpu = getCpuLoad() re...
# Using an Ajax request `Python` ``` @app.route('/_stuff', methods= ['GET']) def stuff(): cpu=round(getCpuLoad()) ram=round(getVmem()) disk=round(getDisk()) return jsonify(cpu=cpu, ram=ram, disk=disk) ``` `Javascript` ``` function update_values() { $SCRIPT_ROOT = {{ request.script_root|t...
Python list_of_tuples: sum second val of each tuple, only if first val of tuple == something
15,722,222
2
2013-03-30T18:55:26Z
15,722,236
9
2013-03-30T18:56:35Z
[ "python", "list", "set", "tuples" ]
I have a list of "tagged" tuples...where each tuple is (tag\_id, value)...like so: ``` my_list = [(tag_A, 100), (tag_A, 200), (tag_A, 300), (tag_A, 400), (tag_B, 400), (tag_B, 600)] ``` I want to sum the values of each tuple with the same tag...so that: ``` sum_of_all_values_with_tag_A() = 1000 sum_of_all_values_wi...
Use a generator expression to sum per tag: ``` sum(val for tag, val in my_list if tag == tag_A) ``` You could *sort* on the tags then use `itertools.groupby` to create per-tag groups and sums: ``` from itertools import groupby from operator import itemgetter key = itemgetter(0) # tag sums = {tag: sum(tup[1] for tu...
sliding window in numpy
15,722,324
3
2013-03-30T19:04:45Z
15,722,507
7
2013-03-30T19:22:31Z
[ "python", "numpy", "time-series", "sliding-window" ]
I have a numpy array of shape (6,2) ``` [[00,01], [10,11], [20,21], [30,31], [40,41], [50,51]] ``` I need a sliding window with step size 1 and window size 3 likes this: ``` [[00,01,10,11,20,21], [10,11,20,21,30,31], [20,21,30,31,40,41], [30,31,40,41,50,51]] ``` I'm looking for a numpy solution. If your sol...
``` In [1]: import numpy as np In [2]: a = np.array([[00,01], [10,11], [20,21], [30,31], [40,41], [50,51]]) In [3]: w = np.hstack((a[:-2],a[1:-1],a[2:])) In [4]: w Out[4]: array([[ 0, 1, 10, 11, 20, 21], [10, 11, 20, 21, 30, 31], [20, 21, 30, 31, 40, 41], [30, 31, 40, 41, 50, 51]]) ``` You co...
"SyntaxError: non-keyword arg after keyword arg" Error in Python when using requests.post()
15,723,294
6
2013-03-30T20:45:21Z
15,723,346
14
2013-03-30T20:50:16Z
[ "python", "post", "arguments" ]
``` response = requests.post("http://api.bf3stats.com/pc/player/", data = player, opt) ``` After running this line in the python IDLE to test things i encounter the syntax error: non-keyword arg after keyword arg. Don't know whats going here. `player` and `opt` are variables that contain a one word string.
Try: `response = requests.post("http://api.bf3stats.com/pc/player/", opt, data=player)` You cannot put a non-keyword argument after a keyword argument. Take a look at the docs at <http://docs.python.org/2.7/tutorial/controlflow.html?highlight=keyword%20args#keyword-arguments> for more info.
Pandas - make a column dtype object or Factor
15,723,628
20
2013-03-30T21:21:57Z
15,723,905
30
2013-03-30T21:54:21Z
[ "python", "pandas" ]
In pandas, how can I convert a column of a DataFrame into dtype object? Or better yet, into a factor? (For those who speak R, in Python, how do I `as.factor()`?) Also, what's the difference between `pandas.Factor` and `pandas.Categorical`?
You can use the [`astype`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html) method to cast a Series (one column): ``` df['col_name'] = df['col_name'].astype(object) ``` Or the entire DataFrame: ``` df = df.astype(object) ``` --- ### Update [Since version 0.15, you can use the categ...
Pandas - make a column dtype object or Factor
15,723,628
20
2013-03-30T21:21:57Z
15,723,994
12
2013-03-30T22:04:14Z
[ "python", "pandas" ]
In pandas, how can I convert a column of a DataFrame into dtype object? Or better yet, into a factor? (For those who speak R, in Python, how do I `as.factor()`?) Also, what's the difference between `pandas.Factor` and `pandas.Categorical`?
`Factor` and `Categorical` are the same, as far as I know. I think it was initially called Factor, and then changed to Categorical. To convert to Categorical maybe you can use `pandas.Categorical.from_array`, something like this: ``` In [27]: df = pd.DataFrame({'a' : [1, 2, 3, 4, 5], 'b' : ['yes', 'no', 'yes', 'no', '...
How to convert Wikipedia wikitable to Python Pandas DataFrame?
15,724,034
8
2013-03-30T22:08:08Z
15,726,212
10
2013-03-31T04:04:52Z
[ "python", "parsing", "pandas", "wiki", "wikipedia" ]
In Wikipedia, you can find some interesting data to be sorted, filtered, ... Here is a sample of a wikitable ``` {| class="wikitable sortable" |- ! Model !! Mhash/s !! Mhash/J !! Watts !! Clock !! SP !! Comment |- | ION || 1.8 || 0.067 || 27 || || 16 || poclbm; power consumption incl. CPU |- | 8200 mGPU || 1.2 || |...
Here's a solution using [py-wikimarkup](https://pypi.python.org/pypi/py-wikimarkup/) and [PyQuery](https://pypi.python.org/pypi/pyquery/) to extract all tables as pandas DataFrames from a wikimarkup string, ignoring non-table content. ``` import wikimarkup import pandas as pd from pyquery import PyQuery def get_table...
Difference between 'python setup.py install' and 'pip install'
15,724,093
20
2013-03-30T22:13:23Z
15,731,459
26
2013-03-31T16:09:47Z
[ "python", "virtualenv", "pip", "setup.py" ]
So I have an external package I want to install into my python virtualenv in a tar file. What is the best way to install the package? I've discovered 2 ways that can do it: 1) Extract the tar file, then run 'python setup.py install' inside of the extracted directory. 2) 'pip install packagename.tar.gz' from example # ...
On the surface, both do the same thing: doing either `python setup.py install` or `pip install <PACKAGE-NAME>` will install your python package for you, with a minimum amount of fuss. However, using pip offers some additional advantages that make it much nicer to use. * pip will automatically download all dependencie...
Installing lxml with enthought Python on Amazon ec2 ubuntu instance
15,724,149
2
2013-03-30T22:20:07Z
16,867,536
8
2013-05-31T23:44:14Z
[ "python", "ubuntu", "amazon-ec2", "lxml", "enthought" ]
I successfully installed enthought Python on ubuntu (running in Amazon EC2 instance). However, I get the following error (log inserted) when trying to install the lxml package ``` /usr/local/bin/pip run on Sat Mar 30 22:05:14 2013 Downloading/unpacking lxml Running setup.py egg_info for package lxml /usr/lib/python2...
I found the same issue on my instance. It turned out to be that compiling lxml takes a lot of memory and my instance was running out of RAM, so the kernel was killing the compiler. To check if you have the same issue, try running `dmesg|tail` after the failure. You'll see some lines like: ``` [2242482.581361] Out of ...
Python: OSError: [Errno 2] No such file or directory: ''
15,725,273
8
2013-03-31T01:04:57Z
15,725,337
16
2013-03-31T01:17:34Z
[ "python", "python-2.7", "python-module" ]
I have a 100 lines, 3 years old python scraper that now bug. Starting lines are: ``` import urllib, re, os, sys, time # line 1: import modules os.chdir(os.path.dirname(sys.argv[0])) # line 2: all works in script's folder > relative address # (rest of my script here!) ``` When run, ``` $cd /my/folder/ $python scri...
Use `os.path.abspath()`: ``` os.chdir(os.path.dirname(os.path.abspath(sys.argv[0]))) ``` `sys.argv[0]` in your case is *just* a script name, no directory, so `os.path.dirname()` returns an empty string. [`os.path.abspath()`](http://docs.python.org/2/library/os.path.html#os.path.abspath) turns that into a proper abso...
Python: OSError: [Errno 2] No such file or directory: ''
15,725,273
8
2013-03-31T01:04:57Z
15,725,342
20
2013-03-31T01:19:02Z
[ "python", "python-2.7", "python-module" ]
I have a 100 lines, 3 years old python scraper that now bug. Starting lines are: ``` import urllib, re, os, sys, time # line 1: import modules os.chdir(os.path.dirname(sys.argv[0])) # line 2: all works in script's folder > relative address # (rest of my script here!) ``` When run, ``` $cd /my/folder/ $python scri...
Have you noticed that you don't get the error if you run ``` python ./script.py ``` instead of ``` python script.py ``` This is because `sys.argv[0]` will read `./script.py` in the former case, which gives `os.path.dirname` something to work with. When you don't specify a path, `sys.argv[0]` reads simply `script.py...
Python: Check if element is not in two lists?
15,725,653
4
2013-03-31T02:14:55Z
15,725,666
8
2013-03-31T02:16:48Z
[ "python", "list", "if-statement" ]
I need to check if an element is not in two lists, currently I have ``` if ele not in lista: if ele not in listb: do stuff ``` Using the following did not work, is there a more efficient way to accomplish the above in python? ``` if ele not in lista and listb: do stuff ```
``` if ele not in lista and ele not in listb: # do stuff ``` or ``` if ele not in lista + listb: # do stuff ``` but the second option will involve list concatenation which could potentially cause memory issues with large lists, also it will have to go through the list twice. To remedy this you could use `ite...
pass build_ext options to pip install
15,725,869
14
2013-03-31T02:55:44Z
19,253,719
7
2013-10-08T16:51:40Z
[ "python", "build", "install", "pip" ]
Is there some way to pass `build_ext` options to pip install to alter how an extension included in a package is compiled? (Yes, I know that one can download the source and build/install with a custom `setup.cfg`, but I'm curious whether it is possible to pass options that can be specified in `setup.cfg` directly throug...
You can create `.pydistutils.cfg` file in your home directory and override build options like you could do with custom `setup.cfg`, but without need to unpack package first. So, for example, you can write something like this to alter include & lib search path: ``` [build_ext] include_dirs=/usr/local/include library_d...
pass build_ext options to pip install
15,725,869
14
2013-03-31T02:55:44Z
31,772,244
7
2015-08-02T13:13:49Z
[ "python", "build", "install", "pip" ]
Is there some way to pass `build_ext` options to pip install to alter how an extension included in a package is compiled? (Yes, I know that one can download the source and build/install with a custom `setup.cfg`, but I'm curious whether it is possible to pass options that can be specified in `setup.cfg` directly throug...
It's possible using `pip --global-option=build_ext`. For example this is `requirements.txt` for Pillow with PNG and JPEG support and no other external libraries: ``` pillow \ --global-option="build_ext" \ --global-option="--enable-zlib" \ --global-option="--enable-jpeg" \ --global-opti...
Python: Using pdb with Flask application
15,726,340
4
2013-03-31T04:28:40Z
15,726,373
8
2013-03-31T04:33:19Z
[ "python", "flask", "pdb" ]
I'm using Flask 0.9 with Python 2.7.1 within a virtualenv, and starting my app with `foreman start` In other apps I've built when I add the following line to my app: ``` import pdb; pdb.set_trace() ``` then reload the browser window, my terminal window displays the pdb interactive debugger: ``` (pdb) ``` However i...
This is because you're using Foreman, which captures the standard output. To debug your app with `pdb`, you'll need to "manually" run it, using `python app.py` or whatever you use. Alternatively, you can use [WinPDB](http://winpdb.org/) (which, despite the name, has *nothing* to do with the operating system), which w...
using python logging in multiple modules
15,727,420
61
2013-03-31T07:39:09Z
15,727,525
11
2013-03-31T07:54:53Z
[ "python", "logging", "config" ]
I have a small python project that has the following structure - ``` Project -- pkg01 -- test01.py -- pkg02 -- test02.py -- logging.conf ``` I plan to use the default logging module to print messages to stdout and a log file. To use the logging module, some initialization is required - ``` import logging.c...
I always do it as below. Use a single python file to config my log as singleton pattern which named '`log_conf.py`' ``` #-*-coding:utf-8-*- import logging.config def singleton(cls): instances = {} def get_instance(): if cls not in instances: instances[cls] = cls() return instance...
using python logging in multiple modules
15,727,420
61
2013-03-31T07:39:09Z
15,729,700
27
2013-03-31T13:11:36Z
[ "python", "logging", "config" ]
I have a small python project that has the following structure - ``` Project -- pkg01 -- test01.py -- pkg02 -- test02.py -- logging.conf ``` I plan to use the default logging module to print messages to stdout and a log file. To use the logging module, some initialization is required - ``` import logging.c...
Actually every logger is a child of the parent's package logger (i.e. `package.subpackage.module` inherits configuration from `package.subpackage)`, so all you need to do is just to configure the root logger. This can be achieved by [`logging.config.fileConfig`](https://docs.python.org/2/library/logging.config.html#log...
using python logging in multiple modules
15,727,420
61
2013-03-31T07:39:09Z
15,735,146
97
2013-03-31T22:09:26Z
[ "python", "logging", "config" ]
I have a small python project that has the following structure - ``` Project -- pkg01 -- test01.py -- pkg02 -- test02.py -- logging.conf ``` I plan to use the default logging module to print messages to stdout and a log file. To use the logging module, some initialization is required - ``` import logging.c...
Best practice is, in each module, to have a logger defined like this: ``` import logging logger = logging.getLogger(__name__) ``` near the top of the module, and then in other code in the module do e.g. ``` logger.debug('My message with %s', 'variable data') ``` If you need to subdivide logging activity inside a mo...
Java equivalent of Python 'in' - for set membership test?
15,727,885
8
2013-03-31T08:51:36Z
15,727,914
12
2013-03-31T08:55:52Z
[ "java", "python", "set", "membership" ]
I want to check if an `item` exists in an `item set`. I want to do this in **java**: ``` def is_item_in_set(item, item_set): if item in item_set: return true else: return false ``` *(Apologies if my python is not pythonic. Just wanted to convey my intent.)* I've managed writing this: ``` bo...
You can't do it with a straight array, but you can with a [`Set<T>`](http://docs.oracle.com/javase/7/docs/api/java/util/Set.html) by calling [`.contains`](http://docs.oracle.com/javase/6/docs/api/java/util/Set.html#contains%28java.lang.Object%29). If you feel like you will be doing a lot of `isItemInSet` calls, conside...
Can a variable be used in Python to define decimal places
15,728,321
3
2013-03-31T10:03:02Z
15,728,353
8
2013-03-31T10:07:22Z
[ "python", "floating-point" ]
I'm familiar with the convention of using `%.2f` to set two decimal places for a float but is it in any way possible to change the number to a variable so that the user can state the number of decimal places displayed?
With the older string format operator, you can use `'%.*f' % (decimals, number)`: ``` >>> number = 26.034 >>> '%.*f' % (3, number) '26.034' >>> '%.*f' % (2, number) '26.03' >>> '%.*f' % (1, number) '26.0' ```
Can a variable be used in Python to define decimal places
15,728,321
3
2013-03-31T10:03:02Z
15,728,373
8
2013-03-31T10:09:55Z
[ "python", "floating-point" ]
I'm familiar with the convention of using `%.2f` to set two decimal places for a float but is it in any way possible to change the number to a variable so that the user can state the number of decimal places displayed?
[`.format`](http://docs.python.org/2/library/string.html#format-specification-mini-language) is a nicer, more readable way to handle variable formatting: ``` '{:.{prec}f}'.format(26.034, prec=3) ```
Is any elegant way to make a list contains some integers to become a list contains some tuples?
15,731,581
3
2013-03-31T16:21:24Z
15,731,613
9
2013-03-31T16:24:44Z
[ "python" ]
I have a list ``` a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` Is any elegant way to make them work in pair? My expected out is ``` [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)] ```
``` pairs = zip(*[iter(a)]*2) ``` is a common idiom
Behavior of "round" function in Python
15,732,032
5
2013-03-31T17:02:27Z
15,732,104
7
2013-03-31T17:09:19Z
[ "python", "python-3.x", "rounding" ]
Could anyone explain me this pice of code: ``` >>> round(0.45, 1) 0.5 >>> round(1.45, 1) 1.4 >>> round(2.45, 1) 2.5 >>> round(3.45, 1) 3.5 >>> round(4.45, 1) 4.5 >>> round(5.45, 1) 5.5 >>> round(6.45, 1) 6.5 >>> round(7.45, 1) 7.5 >>> round(8.45, 1) 8.4 >>> round(9.45, 1) 9.4 ``` **Updated** I guess it is because of...
You are right. None of the numbers can be represented exactly. In some cases the fractional part is strictly greater than `0.45` and in some it is strictly less: ``` In [4]: ['%.20f' % val for val in (0.45, 1.45, 2.45, 3.45, 4.45, 5.45, 6.45, 7.45, 8.45, 9.45)] Out[4]: ['0.45000000000000001110', '1.44999999999999995...
Python OrderedDict not keeping element order
15,733,558
42
2013-03-31T19:25:51Z
15,733,571
75
2013-03-31T19:27:29Z
[ "python", "python-2.7", "ordereddictionary" ]
I'm trying to create an OrderedDict object but no sooner do I create it, than the elements are all jumbled. This is what I do: ``` from collections import OrderedDict od = OrderedDict({(0,0):[2],(0,1):[1,9],(0,2):[1,5,9]}) ``` The elements don't stay in the order I assign ``` od OrderedDict([((0, 1), [1, 9]), ((0, ...
Your problem is that you are constructing a `dict` to give the initial data to the `OrderedDict` - this `dict` *doesn't* store any order, so the order is lost before it gets to the `OrderedDict`. The solution is to build from an ordered data type - the easiest being a `list` of `tuple`s: ``` >>> from collections impo...
Convert float number to string with engineering notation (with SI prefixe) in Python
15,733,772
4
2013-03-31T19:48:57Z
15,734,251
8
2013-03-31T20:36:12Z
[ "python", "string", "numbers" ]
I have a float number such as `x=23392342.1` I would like to convert it to a string with engineering notation (with metric prefix) <http://en.wikipedia.org/wiki/Engineering_notation> <http://en.wikipedia.org/wiki/Metric_prefix> So in my example 23392342.1 = 23.3923421E6 = 23.3923421 M (mega) I would like to display...
Here is a function inspired from [Formatting a number with a metric prefix?](http://stackoverflow.com/questions/12181024/formatting-a-number-with-a-metric-prefix?rq=1) ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import math def ToSI(d): incPrefixes = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] decPrefixes = [...
Simple Python UDP Server: trouble receiving packets from clients other than localhost
15,734,219
5
2013-03-31T20:32:42Z
15,734,249
11
2013-03-31T20:36:06Z
[ "python" ]
So, the very simple code that I'm trying to use is here: <http://wiki.python.org/moin/UdpCommunication> (also here): Sending: ``` import socket UDP_IP = "127.0.0.1" UDP_PORT = 5005 MESSAGE = "Hello, World!" print "UDP target IP:", UDP_IP print "UDP target port:", UDP_PORT print "message:", MESSAGE sock = socket.soc...
Try binding to all local interfaces on the receiving side: ``` sock.bind(("", UDP_PORT)) # could also use "0.0.0.0" ``` Note that the behavior of operating systems is not entirely logical (nor consistent) in terms of binding when receiving UDP packets, especially for multicast traffic. This is the behavior you get: ...
I get: "object does not support item assignment" when populating a dictionary
15,734,220
2
2013-03-31T20:32:52Z
15,734,240
7
2013-03-31T20:34:39Z
[ "python", "csv", "dictionary", "variable-assignment" ]
I am new to Python and programming, and am currently working on a script that will eventually colour counties in a US map according to the rate of protestantism. I have run into a problem that has left me dumbfounded, and I can't seem to find any answers. This code reads in a csv file which has the following format: ...
``` # this is a dict # ↓ evanrate = {} # this isn't --. # ↓ | with open(r'C:\Users\Jeroen\documents\hacker1\evanrate.csv') as evanrate: # | parsereader = csv.reader(evanrate, delimite...
Why is Ruby's Float#round behavior different than Python's?
15,735,454
12
2013-03-31T22:45:56Z
15,735,517
11
2013-03-31T22:54:44Z
[ "python", "ruby", "rounding", "floating-accuracy" ]
"[Behavior of “round” function in Python](http://stackoverflow.com/questions/15732032/behavior-of-round-function-in-python)" observes that Python rounds floats like this: ``` >>> round(0.45, 1) 0.5 >>> round(1.45, 1) 1.4 >>> round(2.45, 1) 2.5 >>> round(3.45, 1) 3.5 >>> round(4.45, 1) 4.5 >>> round(5.45, 1) 5.5 >>...
**Summary** Both implementations are confront the same [issues surrounding binary floating point number](http://docs.python.org/2.7/tutorial/floatingpoint.html)s. Ruby operates directly on the floating point number with simple operations (multiply by a power of ten, adjust, and truncate). Python converts the binary ...
Why is Ruby's Float#round behavior different than Python's?
15,735,454
12
2013-03-31T22:45:56Z
15,735,872
7
2013-03-31T23:45:34Z
[ "python", "ruby", "rounding", "floating-accuracy" ]
"[Behavior of “round” function in Python](http://stackoverflow.com/questions/15732032/behavior-of-round-function-in-python)" observes that Python rounds floats like this: ``` >>> round(0.45, 1) 0.5 >>> round(1.45, 1) 1.4 >>> round(2.45, 1) 2.5 >>> round(3.45, 1) 3.5 >>> round(4.45, 1) 4.5 >>> round(5.45, 1) 5.5 >>...
The fundamental difference is: **Python:** *Convert to decimal and then round* **Ruby:**    *Round and then convert to decimal* Ruby is rounding it from the original floating point bit string, but after operating on it with **10*n*.** You can't see the original binary value without looking very closely. The values a...
How can I quickly estimate the distance between two (latitude, longitude) points?
15,736,995
30
2013-04-01T02:44:39Z
15,737,218
55
2013-04-01T03:22:43Z
[ "python", "math", "maps", "mapping", "latitude-longitude" ]
I want to be able to get a estimate of the distance between two (latitude, longitude) points. I want to undershoot, as this will be for A\* graph search and I want it to be **fast**. The points will be at most 800 km apart.
The answers to [Haversine Formula in Python (Bearing and Distance between two GPS points)](http://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points) provide Python implementations that answer your question. Using the implementation below I **performed 100,000 i...
How can I quickly estimate the distance between two (latitude, longitude) points?
15,736,995
30
2013-04-01T02:44:39Z
15,742,266
19
2013-04-01T11:06:20Z
[ "python", "math", "maps", "mapping", "latitude-longitude" ]
I want to be able to get a estimate of the distance between two (latitude, longitude) points. I want to undershoot, as this will be for A\* graph search and I want it to be **fast**. The points will be at most 800 km apart.
Since the distance is relatively small, you can use the equirectangular distance approximation. This approximation is faster than using the Haversine formula. So, to get the distance from your reference point (lat1/lon1) to the point your are testing (lat2/lon2), use the formula below. Important Note: you need to conve...
Extract Text Using PdfMiner and PyPDF2 Merges columns
15,737,806
2
2013-04-01T04:54:37Z
19,179,114
7
2013-10-04T10:33:02Z
[ "python", "pypdf", "pdftotext" ]
I am trying to parse the pdf file text using pdfMiner, but the extracted text gets merged. I am using the pdf file from the following link. [PDF File](http://www.housingnyc.com/downloads/resources/sta_bldngs/2011StatenIslBldgs.pdf) I am good with any type of output (file/string). Here is the code which returns the ex...
I recently struggled with a similar problem, although my pdf had slightly simpler structure. PDFMiner uses classes called "devices" to parse the pages in a pdf fil. The basic device class is the PDFPageAggregator class, which simply parses the text boxes in the file. The converter classes , e.g. TextConverter, XMLConv...
python: add a character to each item in a list
15,738,267
6
2013-04-01T05:46:20Z
15,738,282
14
2013-04-01T05:47:36Z
[ "python" ]
Suppose I have a list of suits of cards as follows: `suits = ["h","c", "d", "s"]` and I want to add a type of card to each suit, so that my result is something like `aces = ["ah","ac", "ad", "as"]` is there an easy way to do this without recreating an entirely new list and using a `for` loop?
This would have to be the 'easiest' way ``` >>> suits = ["h","c", "d", "s"] >>> aces = ["a" + suit for suit in suits] >>> aces ['ah', 'ac', 'ad', 'as'] ```
python: a quick way to return list without a specific element
15,738,700
9
2013-04-01T06:29:25Z
15,738,712
14
2013-04-01T06:30:19Z
[ "python" ]
If I have a list of card suits in arbitrary order like so: ``` suits = ["h", "c", "d", "s"] ``` and I want to return a list without the `'c'` ``` noclubs = ["h", "d", "s"] ``` is there a simple way to do this?
``` suits = ["h","c", "d", "s"] noclubs = [x for x in suits if x != "c"] ```
python: a quick way to return list without a specific element
15,738,700
9
2013-04-01T06:29:25Z
15,738,716
15
2013-04-01T06:30:35Z
[ "python" ]
If I have a list of card suits in arbitrary order like so: ``` suits = ["h", "c", "d", "s"] ``` and I want to return a list without the `'c'` ``` noclubs = ["h", "d", "s"] ``` is there a simple way to do this?
``` >>> suits = ["h","c", "d", "s"] >>> noclubs = list(suits) >>> noclubs.remove("c") >>> noclubs ['h', 'd', 's'] ``` If you don't need a seperate `noclubs` ``` >>> suits = ["h","c", "d", "s"] >>> suits.remove("c") ```