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 |
|---|---|---|---|---|---|---|---|---|---|
Recursive functions : Inversing word | 40,142,476 | <p>I'm trying to make a simple function that inverses a string using recursion.</p>
<p>this is what i tried : </p>
<pre><code> def inverse(ch):
if ch=='' :
return ''
else:
return ch[len(ch)]+inverse(ch[1:len(ch)-1])
print inverse('hello')
</code></pre>
<p>And this is w... | 1 | 2016-10-19T22:21:57Z | 40,143,066 | <p>You don't really need recursion here.</p>
<pre><code>def inverse(chars):
char_list = list(chars)
char_list.reverse()
return ''.join(char_list)
</code></pre>
| 1 | 2016-10-19T23:23:17Z | [
"python",
"recursion"
] |
Sorting list with dictionaries values(Maximum to Minimum) | 40,142,494 | <p>I have an array with loads of dictionaries in it. However I want to sort dictionaries in a way where I have maximum value to a specific key in a dictionary.
For example I have a list that looks like this</p>
<pre><code>[
{
"num_gurus": 40,
"id": 119749,
"code": null,
"name": "ART... | 1 | 2016-10-19T22:23:40Z | 40,142,543 | <p>try this:</p>
<pre><code>my_list.sort(key=lambda my_dict: my_dict["num_gurus"], reverse=True)
</code></pre>
<p>what this does is basically two things:</p>
<ul>
<li>key paramater expects an anonymous function (lambda in python) and then sorts
the original list values by the values returned by
lambda function. <cod... | 2 | 2016-10-19T22:28:30Z | [
"python",
"arrays",
"sorting",
"dictionary"
] |
Sorting list with dictionaries values(Maximum to Minimum) | 40,142,494 | <p>I have an array with loads of dictionaries in it. However I want to sort dictionaries in a way where I have maximum value to a specific key in a dictionary.
For example I have a list that looks like this</p>
<pre><code>[
{
"num_gurus": 40,
"id": 119749,
"code": null,
"name": "ART... | 1 | 2016-10-19T22:23:40Z | 40,142,577 | <p>For <strong><em>storing the sorted list as new list</em></strong>, you can do it using <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow"><code>sorted()</code></a> as:</p>
<pre><code>sorted(my_list, key=lambda x: x['num_gurus'], reverse=True)
# returns sorted list
</code></pre>
<p>whe... | 1 | 2016-10-19T22:31:14Z | [
"python",
"arrays",
"sorting",
"dictionary"
] |
Scrapy spider for JSON response is giving me error | 40,142,538 | <pre><code>import json
import scrapy
class SpidyQuotesSpider(scrapy.Spider):
name = 'hotelspider'
start_urls = [
'https://tr.hotels.com/search/listings.json?destination-id=1648683&q-check-out=2016-10-22&q-destination=Didim,+T%C3%BCrkiye&q-room-0-adults=2&pg=2&q-rooms=1&start-index... | 0 | 2016-10-19T22:28:03Z | 40,143,370 | <p>I can't seem to reproduce your error but upon copying your code, I got a key error which pertains to your yield statement. See the code below:</p>
<pre><code>import scrapy
import json
class SpidyQuotesSpider(scrapy.Spider):
name = "hotelspider"
allowed_domains = ["tr.hotels.com"]
start_urls = (
... | 0 | 2016-10-19T23:56:31Z | [
"python",
"json",
"python-2.7",
"scrapy",
"scrapy-spider"
] |
Django choices and dictionary | 40,142,646 | <p>I have code</p>
<pre><code>JOBS = 1
CATEGORY_CHOICES = ((JOBS, "Jobs"),)
</code></pre>
<p>And code in the model</p>
<pre><code>category = models.IntegerField(choices=CATEGORY_CHOICES, default=JOBS)
</code></pre>
<p>Instead of "jobs" I want to add a dictionary and have access to it in the template. For example</p... | 0 | 2016-10-19T22:38:43Z | 40,142,718 | <p>Tuples are immutable.I Think it's impossible.</p>
| -2 | 2016-10-19T22:45:47Z | [
"python",
"django",
"dictionary"
] |
Django choices and dictionary | 40,142,646 | <p>I have code</p>
<pre><code>JOBS = 1
CATEGORY_CHOICES = ((JOBS, "Jobs"),)
</code></pre>
<p>And code in the model</p>
<pre><code>category = models.IntegerField(choices=CATEGORY_CHOICES, default=JOBS)
</code></pre>
<p>Instead of "jobs" I want to add a dictionary and have access to it in the template. For example</p... | 0 | 2016-10-19T22:38:43Z | 40,142,877 | <p>Choices in Django models are <code>(key, value)</code> tuples. The key is what's meant to be stored in the model's field when saved and the value is meant to be what's displayed as an option. You can't simply jam a dictionary into the value.</p>
<p>For example, the below choices would store <code>human</code> in th... | 2 | 2016-10-19T23:02:43Z | [
"python",
"django",
"dictionary"
] |
Django choices and dictionary | 40,142,646 | <p>I have code</p>
<pre><code>JOBS = 1
CATEGORY_CHOICES = ((JOBS, "Jobs"),)
</code></pre>
<p>And code in the model</p>
<pre><code>category = models.IntegerField(choices=CATEGORY_CHOICES, default=JOBS)
</code></pre>
<p>Instead of "jobs" I want to add a dictionary and have access to it in the template. For example</p... | 0 | 2016-10-19T22:38:43Z | 40,142,938 | <p>I would comment, but sadly not enough rep. The way <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.IntegerField" rel="nofollow">IntegerField</a> is setup, it displays the dictionary value and returns the dictionary key.</p>
<p>What it seems you want to do is have that key determi... | 1 | 2016-10-19T23:08:29Z | [
"python",
"django",
"dictionary"
] |
converting non-numeric to numeric value using Panda libraries | 40,142,686 | <p>I am a machine learning beginner and wan't to learn ML using python and it's pandas module. So I have a Dataframe like this:</p>
<pre><code>COL1 COL2 COL3
a 9/8/2016 2
b 12/4/2016 23
...
n 1/1/2015 21
</code></pre>
<p>COL1 is a String, Col2 is a timestamp and Col3 is a numbe... | 1 | 2016-10-19T22:42:47Z | 40,142,930 | <p>To encode non-numeric data to numeric you can use scikit-learn's <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html#sklearn.preprocessing.LabelEncoder" rel="nofollow">LabelEncoder</a>. It will encode each category such as COL1's <code>a</code>, <code>b</code>, <code>c</... | 1 | 2016-10-19T23:07:47Z | [
"python",
"pandas"
] |
converting non-numeric to numeric value using Panda libraries | 40,142,686 | <p>I am a machine learning beginner and wan't to learn ML using python and it's pandas module. So I have a Dataframe like this:</p>
<pre><code>COL1 COL2 COL3
a 9/8/2016 2
b 12/4/2016 23
...
n 1/1/2015 21
</code></pre>
<p>COL1 is a String, Col2 is a timestamp and Col3 is a numbe... | 1 | 2016-10-19T22:42:47Z | 40,142,943 | <p>You could convert COL1 with something like this: </p>
<pre><code>import pandas as pd
import string
table = pd.DataFrame([
['a','9/8/2016',2],
['b','12/4/2016',23],
['n','1/1/2015',21],
], columns=['COL1', 'COL2', 'COL3'])
table['COL1'] = table['COL1'].map(dict(zip(list(string.lowercase), xrange(0,25))))... | 1 | 2016-10-19T23:08:47Z | [
"python",
"pandas"
] |
Collision Between two sprites - Python 3.5.2 | 40,142,731 | <p>I have an image of a ufo and a missile. I'm trying to get it to where if the missile hits the ufo they both would explode and disappear and then a few moments later another ufo would respawn but the collision code isn't working. can someone explain to me how to make the code work?</p>
<pre><code>pygame.display.init... | 0 | 2016-10-19T22:46:59Z | 40,143,239 | <p>Well there are many different ways to detect collision, And it might be worth looking at libraries that would do so, but the simplest method by far is to use <code>pygame.sprite.spritecollide()</code>.</p>
<p>But before I can show how to use the function, you need to know what a <code>pygame.sprite.Group()</code> i... | 2 | 2016-10-19T23:41:38Z | [
"python",
"pygame",
"collision-detection"
] |
How to do curvefitting using scipy.optimize.curve_fit | 40,142,752 | <p>I am quite new to Python. I wanted to do a sum of exponentials fit to my data using curve_fit. Here's my code:</p>
<pre><code>import numpy as np
from scipy.optimize import curve_fit
xdata= np.array('1, 8, 8, 21, 31, 42, 63, 64, 81, 110, 156, 211, 301, 336, 735')
ydata = np.array('0.018, 0.0164, 0.0042, 0.0072, 0.0... | 0 | 2016-10-19T22:49:06Z | 40,142,816 | <pre><code>import numpy as np
from scipy.optimize import curve_fit
xdata= np.array([1, 8, 8, 21, 31, 42, 63, 64, 81, 110, 156, 211, 301, 336, 735])
ydata = np.array([0.018, 0.0164, 0.0042, 0.0072, 0.0108, 0.0044, 0.0035, 0.0036, 0.0042, 0.0051, 0.0019, 0.0042, 0.0019, 8e-4, 2e-4])
def func(x,a,b,m,n):
return a*np... | 0 | 2016-10-19T22:55:57Z | [
"python",
"optimization",
"scipy"
] |
Python Array Reshaping Issue to Array with Shape (None, 192) | 40,142,804 | <p>I have this error and I'm not sure how do I reshape where there's a dimension with <code>None</code>.</p>
<pre><code>Exception: Error when checking : expected input_1 to have shape (None, 192) but got array with shape (192, 1)
</code></pre>
<p>How do I reshape an array to (None, 192)? </p>
<p>I've the array <code... | 0 | 2016-10-19T22:54:26Z | 40,142,832 | <p>This is an error in the library code, because <code>(None, 192)</code> is an invalid shape for a numpy array - the shape must be a tuple of integers. </p>
<p>To investigate any further, we'll have to see the traceback and/or the code which is raising that exception. </p>
| 0 | 2016-10-19T22:57:44Z | [
"python",
"numpy",
"keras"
] |
Different result for String and Integers using JSON in python | 40,142,811 | <p><strong>EDIT:</strong>
As @Alfe suggested in the comments, the exact problem in this case is that the following code is unable to handle nodes with same values. So, How do I get the expected output, without changing the value of the nodes?</p>
<p>I'm executing following code to make a tree from JSON data:</p>
<pre... | 2 | 2016-10-19T22:55:05Z | 40,142,876 | <p>That is actually how your data is:</p>
<pre><code>>>> s = '{"92": {"children": [{"87": {"children": [87, 96]}}, {"96": {"children": [90, 105]}}]}}'
>>> print(json.dumps(json.loads(s), indent=2))
{
"92": {
"children": [
{
"87": {
"children": [
87,
... | 0 | 2016-10-19T23:02:41Z | [
"python",
"json",
"tree"
] |
Different result for String and Integers using JSON in python | 40,142,811 | <p><strong>EDIT:</strong>
As @Alfe suggested in the comments, the exact problem in this case is that the following code is unable to handle nodes with same values. So, How do I get the expected output, without changing the value of the nodes?</p>
<p>I'm executing following code to make a tree from JSON data:</p>
<pre... | 2 | 2016-10-19T22:55:05Z | 40,142,893 | <p>Editting based on the <em>edit</em> in the question:</p>
<p>As far as your output is considered, it is giving me:</p>
<pre><code>92 -> 87;
87 -> 87;
87 -> 96;
92 -> 96;
96 -> 90;
96 -> 105;
</code></pre>
<p>It is showing <code>"87"</code> and <code>87</code> as same because you are using <code>.... | 2 | 2016-10-19T23:04:26Z | [
"python",
"json",
"tree"
] |
Restarting a function in Python 3.4 | 40,142,901 | <p>I need help for my python assignment. We have to make a quiz program and I am having trouble with restarting a function.</p>
<p>I need something like continue, but instead runs the function again. Also, some tips on returning values from functions cant hurt! Thanks! ~Also, I just started using python 2 weeks ago, s... | -2 | 2016-10-19T23:05:07Z | 40,143,037 | <p>To capture the return of the <code>modMode</code> function, <strong>just make sure you return something at the end</strong>:</p>
<pre><code>score = 0;
modPassword = "200605015"
def modMode(score):
print("Entering Overide Mode")
print("Opening Overide Console")
cmd = input("Enter Command: ")
if cmd == "... | 1 | 2016-10-19T23:19:40Z | [
"python",
"function",
"return",
"python-3.4"
] |
can't assign to function call Error-Python | 40,142,906 | <p>So I'm working on a project to create a postal bar code out of an inputted 5 digit zipcode
this is what i have so far and i'm not sure why i'm getting this error or how to approach fixing it, appreciate the help!</p>
<pre><code>zipcode=input("What is your 5 digit zipcode?")
s=zipcode.split(",")
def correctiondigit... | 2 | 2016-10-19T23:05:34Z | 40,142,953 | <p>Your error is here:</p>
<pre><code>for barcode(a) in s:
</code></pre>
<p>It's invalid syntax because the name bound in a for loop has to be a python identifier. </p>
<p>You were probably trying for something like this instead:</p>
<pre><code>for the_zipcode in s:
print(barcode(the_zipcode))
</code></pre>
| 2 | 2016-10-19T23:09:42Z | [
"python",
"syntax-error",
"barcode"
] |
can't assign to function call Error-Python | 40,142,906 | <p>So I'm working on a project to create a postal bar code out of an inputted 5 digit zipcode
this is what i have so far and i'm not sure why i'm getting this error or how to approach fixing it, appreciate the help!</p>
<pre><code>zipcode=input("What is your 5 digit zipcode?")
s=zipcode.split(",")
def correctiondigit... | 2 | 2016-10-19T23:05:34Z | 40,143,290 | <p>I am fairly certain your problem is your use of <code>s=zipcode.split(",")</code>. What that does is split the string that is put in by the user (if you're using python 3) into an array of strings, where each element is delimited by a comma. For example:</p>
<pre><code>'11111'.split(',') # ['11111']
'11111,12345'.s... | 0 | 2016-10-19T23:46:58Z | [
"python",
"syntax-error",
"barcode"
] |
How do you make it so that a function returns a tuple divided in multiple lines? | 40,142,948 | <p>Basically I have a tuple which has 5 tuples in it. How do I make it so that my function returns that same tuple in multiple lines instead of one?</p>
<p>Example:</p>
<pre><code>>>> hello = (('1','2'),('3','4'),('5','6'),('7','8'),('9','10'))
>>> function(hello)
(('1','2'),
('3','4'),
... | -2 | 2016-10-19T23:09:22Z | 40,143,096 | <p>Hereâs the quick and dirty way:</p>
<pre><code>def formatted_tuple(x):
st = '%s' % (x,)
return st.replace('),', '),\n')
# now you can call formatted_tuple(hello)
</code></pre>
| 0 | 2016-10-19T23:26:15Z | [
"python",
"tuples"
] |
error handling with BeautifulSoup when scraped url doesn't respond | 40,143,133 | <p>I'm totally noob to python so please forgive my mistake and lack of vocabulary. I'm trying to scrap some url with BeautifulSoup. My url are coming from a GA api call and some of them doesn't respond. </p>
<p>How do I build my script so that BeautifulSoup ignore the url that doesn't return anything ? </p>
<p>Here i... | 1 | 2016-10-19T23:29:37Z | 40,143,231 | <p>You may check the value of <code>name_box</code> variable - it would be <code>None</code> if nothing found:</p>
<pre><code>for row in urllist[4:8]:
page = urllib2.urlopen(row)
soup = BeautifulSoup(page, 'html.parser')
name_box = soup.find(attrs={'class': 'nb-shares'})
if name_box is None:
... | 1 | 2016-10-19T23:40:22Z | [
"python",
"beautifulsoup"
] |
finding cubed root using delta and epsilon in Python | 40,143,166 | <p>I am trying to write a program that finds cubed root using delta and epsilon but i'm stuck because i cant figure out why my program runs in an infinite loop</p>
<pre><code> num = 100
epsilon = 0.01
guess = num/3.0
while abs(guess**3 - num) >= epsilon:
delta = abs(guess**3 - num)/100
... | 1 | 2016-10-19T23:33:31Z | 40,143,315 | <p>First thing, you should use <code>if/elif</code> instead of separate <code>if</code> blocks. </p>
<p>Consider the following:
when <code>guess**3 > num</code> is <code>True</code>, you update <code>guess</code> by reducing its value so that <code>guess**3 < num</code> (the next if condition) becomes <code>True... | 2 | 2016-10-19T23:49:43Z | [
"python",
"python-3.x"
] |
How to execute multiline python code from a bash script? | 40,143,190 | <p>I need to extend a shell script (bash). As I am much more familiar with python I want to do this by writing some lines of python code which depends on variables from the shell script. Adding an extra python file is not an option.</p>
<pre><code>result=`python -c "import stuff; print('all $code in one very long line... | 1 | 2016-10-19T23:36:01Z | 40,143,212 | <p>Use a here-doc:</p>
<pre><code>result=$(python <<EOF
import stuff
print('all $code in one very long line')
EOF
)
</code></pre>
| 5 | 2016-10-19T23:38:17Z | [
"python",
"bash",
"multiline"
] |
How to execute multiline python code from a bash script? | 40,143,190 | <p>I need to extend a shell script (bash). As I am much more familiar with python I want to do this by writing some lines of python code which depends on variables from the shell script. Adding an extra python file is not an option.</p>
<pre><code>result=`python -c "import stuff; print('all $code in one very long line... | 1 | 2016-10-19T23:36:01Z | 40,143,247 | <p>Tanks to <a href="http://stackoverflow.com/a/37222377/333403">this SO answer</a> I found the answer myself:</p>
<pre><code>#!/bin/bash
# some bash code
END_VALUE=10
PYTHON_CODE=$(cat <<END
# python code starts here
import math
for i in range($END_VALUE):
print(i, math.sqrt(i))
# python code ends here
... | 0 | 2016-10-19T23:42:35Z | [
"python",
"bash",
"multiline"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.