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
sequencelengths 1
5
|
---|---|---|---|---|---|---|---|---|---|
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 what i get : </p>
<blockquote>
<p>line 13, in inverse
return ch[len(ch)]+inverse(ch[1:len(ch)-1]) IndexError: string index out of range</p>
</blockquote>
| 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 198P",
"short_name": "ART 198P",
"title": "Directed Group Study",
"department_long": null,
"full_name": "Directed Group Study",
"department_short": "ART"
},
{
"num_gurus": 3,
"id": 119825,
"code": null,
"name": "ASAMST 198P",
"short_name": "ASAMST 198P",
"title": "Supervised Group Study",
"department_long": null,
"full_name": "Supervised Group Study",
"department_short": "ASAMST"
},
{
"num_gurus": 200,
"id": 119904,
"code": null,
"name": "AST 636",
"short_name": "AST 636",
"title": "Baudelaire: Art Poetry Modernity",
"department_long": null,
"full_name": "Baudelaire: Art Poetry Modernity",
"department_short": "AST"
}
]
</code></pre>
<p>I want my output to sort my dictionaries where the value of a key attribute 'num_gurus' is maximum to minimum. Expected output would be.</p>
<pre><code>[
{
"num_gurus": 200,
"id": 119904,
"code": null,
"name": "AST 636",
"short_name": "AST 636",
"title": "Baudelaire: Art Poetry Modernity",
"department_long": null,
"full_name": "Baudelaire: Art Poetry Modernity",
"department_short": "AST"
}
{
"num_gurus": 40,
"id": 119749,
"code": null,
"name": "ART 198P",
"short_name": "ART 198P",
"title": "Directed Group Study",
"department_long": null,
"full_name": "Directed Group Study",
"department_short": "ART"
},
{
"num_gurus": 3,
"id": 119825,
"code": null,
"name": "ASAMST 198P",
"short_name": "ASAMST 198P",
"title": "Supervised Group Study",
"department_long": null,
"full_name": "Supervised Group Study",
"department_short": "ASAMST"
}
]
</code></pre>
<p>I have tried this so far</p>
<pre><code> for items in load_as_json:
for key, val in sorted(items['num_gurus'].iteritems(), key=lambda (k,v): (v,k), reverse=True):
print key,val
This throws me error and doesn't do what I actually want to.
This is the error I got.
File "utils.py", line 61, in GetPopularCoursesBasedOnGurus
for key, val in sorted(str(items['num_gurus']).iteritems(), key=lambda (k,v): (v,k)):
AttributeError: 'str' object has no attribute 'iteritems'
</code></pre>
| 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. <code>lambda my_dict: my_dict["num_gurus"]</code> returns the "num_gurus" item within each dictionary hence the list is sorted by those values.</li>
<li><code>reverse=True</code> by default sort function sorts from min to max, hence
this simply reverses that</li>
</ul>
<p>also I find this very "unsafe" as you have no guarentee for "num_gurus" key within your dictionaries, or a dictionary as a key value, hence I'd personally wrap this with some exception handler: <code>try</code> \ <code>except</code></p>
<p>read more here: <a href="https://docs.python.org/2.7/tutorial/errors.html" rel="nofollow">https://docs.python.org/2.7/tutorial/errors.html</a>, remember better safe than sorry!</p>
| 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 198P",
"short_name": "ART 198P",
"title": "Directed Group Study",
"department_long": null,
"full_name": "Directed Group Study",
"department_short": "ART"
},
{
"num_gurus": 3,
"id": 119825,
"code": null,
"name": "ASAMST 198P",
"short_name": "ASAMST 198P",
"title": "Supervised Group Study",
"department_long": null,
"full_name": "Supervised Group Study",
"department_short": "ASAMST"
},
{
"num_gurus": 200,
"id": 119904,
"code": null,
"name": "AST 636",
"short_name": "AST 636",
"title": "Baudelaire: Art Poetry Modernity",
"department_long": null,
"full_name": "Baudelaire: Art Poetry Modernity",
"department_short": "AST"
}
]
</code></pre>
<p>I want my output to sort my dictionaries where the value of a key attribute 'num_gurus' is maximum to minimum. Expected output would be.</p>
<pre><code>[
{
"num_gurus": 200,
"id": 119904,
"code": null,
"name": "AST 636",
"short_name": "AST 636",
"title": "Baudelaire: Art Poetry Modernity",
"department_long": null,
"full_name": "Baudelaire: Art Poetry Modernity",
"department_short": "AST"
}
{
"num_gurus": 40,
"id": 119749,
"code": null,
"name": "ART 198P",
"short_name": "ART 198P",
"title": "Directed Group Study",
"department_long": null,
"full_name": "Directed Group Study",
"department_short": "ART"
},
{
"num_gurus": 3,
"id": 119825,
"code": null,
"name": "ASAMST 198P",
"short_name": "ASAMST 198P",
"title": "Supervised Group Study",
"department_long": null,
"full_name": "Supervised Group Study",
"department_short": "ASAMST"
}
]
</code></pre>
<p>I have tried this so far</p>
<pre><code> for items in load_as_json:
for key, val in sorted(items['num_gurus'].iteritems(), key=lambda (k,v): (v,k), reverse=True):
print key,val
This throws me error and doesn't do what I actually want to.
This is the error I got.
File "utils.py", line 61, in GetPopularCoursesBasedOnGurus
for key, val in sorted(str(items['num_gurus']).iteritems(), key=lambda (k,v): (v,k)):
AttributeError: 'str' object has no attribute 'iteritems'
</code></pre>
| 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>where <code>my_list</code> is your <code>list</code> of <code>dict</code> objects.</p>
<p>Else, if you want to <strong><em>sort the content of original list</em></strong>, i.e <code>my_list</code>, then use <code>list.sort()</code> as:</p>
<pre><code>my_list.sort(key=lambda x: x["num_gurus"], reverse=True)
# sorts the original list
</code></pre>
<p>Check document on: <a href="https://wiki.python.org/moin/HowTo/Sorting" rel="nofollow">How to do Sorting in list</a></p>
| 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=7&q-check-in=2016-10-21&resolved-location=CITY:1648683:UNKNOWN:UNKNOWN&q-room-0-children=0&pn=1'
]
def parse(self, response):
myresponse = json.loads(response.body)
data = myresponse.get('data')
body = data.get('body')
searchresults = body.get('searchResults')
for item in searchresults.get('results', []):
yield {
'text': item[0]['altText']
}
</code></pre>
<p><a href="https://i.stack.imgur.com/QzKuk.png" rel="nofollow">this is the screenshot of the error</a></p>
<p>I always get error when I run this script. Can anybody help me where I am doing wrong ? </p>
| 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 = (
'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=7&q-check-in=2016-10-21&resolved-location=CITY:1648683:UNKNOWN:UNKNOWN&q-room-0-children=0&pn=1',
)
def parse(self, response):
myresponse = json.loads(response.body)
data = myresponse.get('data')
body = data.get('body')
searchresults = body.get('searchResults')
for item in searchresults.get('results', []):
yield {
'text': item['altText']
}
</code></pre>
<p>Make sure you are indenting using the same amount of spaces or just use TAB. Though the indentation shown in your code seems fine. Try pasting mine and see what comes up.</p>
| 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>
<pre><code>JOBS = 1
CATEGORY_CHOICES = ((JOBS, {'title':"Jobs",'icon':"fa fa-briefcase",'slug':"jobs"}),)
</code></pre>
<p>But instead I get the following</p>
<p><a href="https://i.stack.imgur.com/Oc7Jw.png" rel="nofollow"><img src="https://i.stack.imgur.com/Oc7Jw.png" alt="enter image description here"></a></p>
<p>How to add the dictionary into the choices?
I was able to create a model, which would be set up: title and icon. But instead, I decided to create a choice. Title I can add, but for the selected item to set the icon?</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>
<pre><code>JOBS = 1
CATEGORY_CHOICES = ((JOBS, {'title':"Jobs",'icon':"fa fa-briefcase",'slug':"jobs"}),)
</code></pre>
<p>But instead I get the following</p>
<p><a href="https://i.stack.imgur.com/Oc7Jw.png" rel="nofollow"><img src="https://i.stack.imgur.com/Oc7Jw.png" alt="enter image description here"></a></p>
<p>How to add the dictionary into the choices?
I was able to create a model, which would be set up: title and icon. But instead, I decided to create a choice. Title I can add, but for the selected item to set the icon?</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 the database and display <code>Humans</code> in a select field.</p>
<pre><code>species = [
('human', 'Humans'),
('reptile', 'Reptiles'),
('cylons', 'Aliens'),
]
</code></pre>
<p>Instead, you need to restructure how your model your data. You should create a separate <code>Category</code> model that represents the choices which will contain fields for a slug, icon and title.</p>
<pre><code>class Category(models.Model):
slug = models.SlugField()
title = models.CharField()
icon = models.CharField()
</code></pre>
<p>You then point your current model at the <code>Category</code> model using a <code>ForeignKey()</code>. </p>
<pre><code>class MyModel(models.Model):
category = models.ForeignKey(Category)
</code></pre>
<p>Finally, you can use a <a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/#modelchoicefield" rel="nofollow"><code>ModelChoiceField</code></a> when rendering the form to render the related category models (related across the foreign key) as choices in a list. If you use a <a href="https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/" rel="nofollow"><code>ModelForm</code></a>, all foreign keys will be represented as <a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/#modelchoicefield" rel="nofollow"><code>ModelChoiceField</code></a>s by default.</p>
| 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>
<pre><code>JOBS = 1
CATEGORY_CHOICES = ((JOBS, {'title':"Jobs",'icon':"fa fa-briefcase",'slug':"jobs"}),)
</code></pre>
<p>But instead I get the following</p>
<p><a href="https://i.stack.imgur.com/Oc7Jw.png" rel="nofollow"><img src="https://i.stack.imgur.com/Oc7Jw.png" alt="enter image description here"></a></p>
<p>How to add the dictionary into the choices?
I was able to create a model, which would be set up: title and icon. But instead, I decided to create a choice. Title I can add, but for the selected item to set the icon?</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 determine the results of several other values. What you should do then is in whatever view you submit that form to, set those other values based on the key returned by your IntegerField.</p>
<p>In other words:</p>
<pre><code>CATEGORY_CHOICES = ((1, 'Jobs'),(2, 'Cities'),)
</code></pre>
<p>Then later in the class or view that this form is submitted to:</p>
<pre><code>if CATEGORY_CHOICES == 1:
title = 'Jobs'
icon = 'fa fa-briefcase'
slug = 'jobs'
elif CATEGORY_CHOICES == 2:
title = 'Cities'
` icon = 'fa fa-city'
slug = 'cities'
</code></pre>
| 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 number. Now I need to do some analysis on this Dataframe and I want to convert all the non-numeric data to numeric. I tried using <a href="http://scikit-learn.org/stable/modules/feature_extraction.html#dict-feature-extraction" rel="nofollow">DictVectorizer()</a> to convert COL1 and 2 to numeric but first of all I am not sure if this is the best way doing such a thing and second I don't know what to do with the timestamp.
When I use DictVectorizer the output would be like:</p>
<pre><code>{u'COL3: {0:2, 1:23 , ...,n:21}, 'COL1': {0: u'a', 1:'b', ... , n:'n'}, 'COL2': {0: u'9/8/2016' , 1: u'12/4/2016' , ... , n:u'1/1/2016'}}
</code></pre>
<p>but from what I learned it should be like this or at least I know I need something like this:</p>
<pre><code> {COL1:'a', COL2: '9/8/2016' , COL3: 2 and so on}
</code></pre>
<p>so, questions:
1-what is the best way of converting non- numeric (including date) to numeric values to use in sklearn libraries
2- what is the right way of using DictVectorize()</p>
<p>Any help would be appreciated. </p>
| 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</code> to integers.</p>
<p>Assuming df is your dataframe, try:</p>
<pre><code>from sklearn.preprocessing import LabelEncoder
enc = LabelEncoder()
enc.fit(df['COL1'])
df['COL1'] = enc.transform(df['col1'])
</code></pre>
<ul>
<li><code>enc.fit()</code> creates the corresponding integer values.</li>
<li><code>enc.transform()</code> applies the encoding to the df values.</li>
</ul>
<p>For the second column, using Pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">to_datetime()</a> function should do the trick, like @quinn-weber mentioned, try:</p>
<pre><code>df['COL2'] = pd.to_datetime(df['COL2'])
</code></pre>
| 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 number. Now I need to do some analysis on this Dataframe and I want to convert all the non-numeric data to numeric. I tried using <a href="http://scikit-learn.org/stable/modules/feature_extraction.html#dict-feature-extraction" rel="nofollow">DictVectorizer()</a> to convert COL1 and 2 to numeric but first of all I am not sure if this is the best way doing such a thing and second I don't know what to do with the timestamp.
When I use DictVectorizer the output would be like:</p>
<pre><code>{u'COL3: {0:2, 1:23 , ...,n:21}, 'COL1': {0: u'a', 1:'b', ... , n:'n'}, 'COL2': {0: u'9/8/2016' , 1: u'12/4/2016' , ... , n:u'1/1/2016'}}
</code></pre>
<p>but from what I learned it should be like this or at least I know I need something like this:</p>
<pre><code> {COL1:'a', COL2: '9/8/2016' , COL3: 2 and so on}
</code></pre>
<p>so, questions:
1-what is the best way of converting non- numeric (including date) to numeric values to use in sklearn libraries
2- what is the right way of using DictVectorize()</p>
<p>Any help would be appreciated. </p>
| 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))))
</code></pre>
<p>As for the timestamp, you could do:</p>
<pre><code>table['COL2'] = pd.to_datetime(
table['COL2'], format='%m/%d/%Y'
).dt.strftime(date_format='%Y%m%d')
</code></pre>
| 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()
pygame.font.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
ufo = pygame.image.load("ufo.png")
rocket = pygame.image.load("rocket.png")
done = False
debug = False
fontObj = pygame.font.SysFont("Courier New", 20)
#Making my Empty Lists
missiles = [] #[x,y]
ufo_list = [] #[x,y,hspeed]
particle_list = []
#UFO Respawn Info
ufoRespawn = True
ufoHits = 0
ufoSpawnTimer = 0.0
ufoSpeed = 500.0
#MISSILE Info
launchX = 400
launchY = 550
missileSpeed = 100.0
missileDirection = 0
#creating the Starfield
myStars = [] # An (initially) empty list
for i in range(1000):
x = random.randint(0, 800)
y = random.randint(0, 600)
newStar = [x, y] # A 2-element list
myStars.append(newStar)
starSpeed = 100.0 # Rate of star movement (px / s)
starDirection = 0 # 0 = not moving, -1 = left, +1 = right
#input
while not done:
event = pygame.event.poll()
if event.type == pygame.QUIT:
done = True
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
debug = not debug
dt = clock.tick() /1000.0
#the missile range (making it disappear after it hits the top)
for missile in missiles:
missile[1] -= missileSpeed * dt
if missile[1] < 0: missiles.remove(missle)
#triangle following mouse position
mx, my = pygame.mouse.get_pos()
if mx > launchX:
launchX += .3
if mx < launchX:
launchX -= .3
#bullets firing when pressing with mouse
mbuttons = pygame.mouse.get_pressed()
if mbuttons [0]:
x = launchX
y = launchY
newMissiles = [x,y]
missiles.append(newMissiles)
#Creating the UFOs
ufoSpawnTimer -= dt
if ufoSpawnTimer <= 0:
if random.choice (("head", "tail")) == "head":
x = 0
hspeed = random.randint (10,50)
else:
x = 800
hspeed = random.randint (-50, -10)
y = random.randint (0,300)
new_ufo = [x,y,hspeed]
ufo_list.append(new_ufo)
ufoSpawnTimer = 5.0
#Moving the Starfield
for i in range(len(myStars)):
myStars[i][0] += starSpeed * dt * starDirection
if myStars[i][0] < 0: myStars[i][0] = 800
if myStars[i][0] > 800: myStars[i][0] = 0
screen.fill ((0,0,0))
#drawing the triangle a.k.a missle launcher :D
pygame.draw.polygon(screen, (255,255,255), [[launchX, launchY], [launchX + 10, launchY + 10], \
[launchX - 10, launchY + 10]], 3)
for missile in missiles:
x = int(missile[0])
y = int(missile[1])
screen.blit(rocket, (x,y))
#drawing the ufo
for v in ufo_list:
v[0] += v[2] * dt
screen.blit(ufo,(v[0],v[1]))
#Missle distance from UFO - NEED HELP ON THIS PORTION
#Hit Detection
missileDist = ((x - v[0]) ** 2 + (y - v[1]) ** 2) ** 0.5
if **????** :
ufoRespawn = True
ufoHits += 10
#drawing th starfield
for star in myStars:
x = int(star[0])
y = int(star[1])
pygame.draw.circle(screen, (255,255,255), (x,y), 2)
pygame.display.flip()
pygame.font.quit()
pygame.display.quit()
</code></pre>
| 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> is and what a sprite class is.</p>
<p>Basicly, what a <code>pygame.sprite.Group()</code> is, is a way to keep track of and hold multiple sprites. In your case, it seems making a missile group for your missiles would be the best choice.</p>
<p>So I would create a group to hold your missiles:
<code>missiles_group = pygame.sprite.Group()</code>. You can add missiles to the group by saying <code>missiles_group.add(<sprite instance name>)</code>.</p>
<p>As for the sprite class, please see this answer I gave to a question. To be terse, a Sprite class is a modular way to create a sprite. Instead of using just a plain image, a sprite class would hold necessary methods and attributes of a sprite. I will be using a sprite class in my example below, so if more detail is needed, please read the answer I linked to above. </p>
<hr>
<p>With that out of the way, and without going into too much detail, here is how you fill in each function parameter to the above function.</p>
<ul>
<li><code>sprite</code>: This is the sprite that will be tested against a group of sprites</li>
<li><code>group</code>: This is the group that will be used to test with the sprite.</li>
<li><code>dokill</code>: This is a boolean value. If set to true, each time the <code>sprite</code> parameter collides with something in the <code>group</code> parameter, and object from the group parameter will be deleted. And visa versa if the <code>dokill</code> argument is set to false.
The is one more parameter that the function takes, but for what you're trying to do, it is not needed.</li>
</ul>
<p>Incorporating the above information, here is an example. The example creates a sprite and a list of sprites. Each time the sprite collides with a sprite from the group, <code>HIT</code> is printed to the screen:</p>
<pre><code>import pygame #import the pygame module into the namespace <module>
WIDTH = 640 # define a constant width for our window
HEIGHT = 480 # define a constant height for our window
#create a pygame window, and
#initialize it with our WIDTH and HEIGHT constants
display = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock() # create a game clock
class Sprite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((20, 20))
self.image.fill((255, 0, 0))
self.rect = self.image.get_rect()
self.rect.x = WIDTH / 2
self.rect.y = HEIGHT / 2
self.vx = 0
self.vy = 0
def update(self):
self.vx = 0
self.vy = 0
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
self.vx = -1
elif key[pygame.K_RIGHT]:
self.vx = 1
if key[pygame.K_UP]:
self.vy = -1
elif key[pygame.K_DOWN]:
self.vy = 1
self.rect.x += self.vx
self.rect.y += self.vy
# cretae a player sprite
player = Sprite()
# create a group to hold all of our sprites
sprites = pygame.sprite.Group()
# create a group to hold sprites we want to
# test collions against. These sprites will
# still be added to the sprites list
# but we need a seperate group to test for
# collisions against
collision_sprites = pygame.sprite.Group()
# add a sprite to out collison sprite group
# We also add the sprite to our sprites group
# that holds all sprites
tmp = Sprite()
tmp.update = lambda: None
sprites.add(tmp)
collision_sprites.add(tmp)
# add a player sprites to the player group
player.rect.x = 10
sprites.add(player)
running = True # our variable for controlling our game loop
while running:
for e in pygame.event.get(): # iterate ofver all the events pygame is tracking
clock.tick(60) # make our clock keep pour game at 60 FPS
if e.type == pygame.QUIT: # is the user trying to close the window?
running = False # if so break the loop
pygame.quit() # quit the pygame module
quit() # quit is for IDLE friendliness
sprites.update()
# here is where we test for collision
if pygame.sprite.spritecollide(player, collision_sprites, False):
print("HIT!")
display.fill((180, 180, 180)) # fill the pygame screen with white
sprites.draw(display)
pygame.display.flip() # update the screen
</code></pre>
<p>My example if fairly big, so take your time and step through it carefully. I tried to add as many good comments as I could. Good luck!</p>
| 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.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.exp(m*x)+b*np.exp(n*x)
curve_fit(func, xdata, ydata)
</code></pre>
<p>I get the typeerror stating: "ufunc 'multiply' did not contain a loop with signature matching types dtype('
<p>Can somebody please help me with this? Also, I would like to set a constraint such that parameters a and b add to 1.</p>
<p>Thank you.</p>
| 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.exp(m*x)+b*np.exp(n*x)
curve_fit(func, xdata, ydata)
</code></pre>
<p>unfortunatly <code>Covariance of the parameters could not be estimated</code></p>
| 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>accuracy</code> with shape <code>(12, 16)</code> and I did <code>accuracy.reshape(-1)</code> that gives <code>(192,)</code>. However this is not <code>(None, 192)</code>.</p>
| 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><code>from __future__ import print_function
import json
import sys
# Tree in JSON format
s = '{"Harry": {"children": ["Bill", {"Jane": {"children": [{"Diane": {"children": ["Mary"]}}, "Mark"]}}]}}'
# Convert JSON tree to a Python dict
data = json.loads(s)
# Extract tree edges from the dict
edges = []
def get_edges(treedict, parent=None):
name = next(iter(treedict.keys()))
if parent is not None:
edges.append((parent, name))
for item in treedict[name]["children"]:
if isinstance(item, dict):
get_edges(item, parent=name)
else:
edges.append((name, item))
get_edges(data)
# Dump edge list in Graphviz DOT format
print('strict digraph tree {')
for row in edges:
print(' {0} -> {1};'.format(*row))
print('}')
</code></pre>
<p>Command used at terminal: <code>python filename.py | dot -Tpng -otree.png</code></p>
<p>With String input, as shown in the code above, the output is:
<a href="https://i.stack.imgur.com/zFvic.png" rel="nofollow"><img src="https://i.stack.imgur.com/zFvic.png" alt="enter image description here"></a></p>
<p>But if I enter JSON data with integers:</p>
<p><code>s = '{"92": {"children": [{"87": {"children": [87, 96]}}, {"96": {"children": [90, 105]}}]}}'</code></p>
<p>I get following output: (which is wrong!)</p>
<p><a href="https://i.stack.imgur.com/aTnbF.png" rel="nofollow"><img src="https://i.stack.imgur.com/aTnbF.png" alt="enter image description here"></a></p>
<p>Expected output:
<a href="https://i.stack.imgur.com/MVkyL.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/MVkyL.jpg" alt="enter image description here"></a></p>
<p>What am I doing wrong here? How to solve this issue?</p>
| 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,
96
]
}
},
{
"96": {
"children": [
90,
105
]
}
}
]
}
}
</code></pre>
<p><code>87</code> is listed as a child of <code>87</code>.</p>
| 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><code>from __future__ import print_function
import json
import sys
# Tree in JSON format
s = '{"Harry": {"children": ["Bill", {"Jane": {"children": [{"Diane": {"children": ["Mary"]}}, "Mark"]}}]}}'
# Convert JSON tree to a Python dict
data = json.loads(s)
# Extract tree edges from the dict
edges = []
def get_edges(treedict, parent=None):
name = next(iter(treedict.keys()))
if parent is not None:
edges.append((parent, name))
for item in treedict[name]["children"]:
if isinstance(item, dict):
get_edges(item, parent=name)
else:
edges.append((name, item))
get_edges(data)
# Dump edge list in Graphviz DOT format
print('strict digraph tree {')
for row in edges:
print(' {0} -> {1};'.format(*row))
print('}')
</code></pre>
<p>Command used at terminal: <code>python filename.py | dot -Tpng -otree.png</code></p>
<p>With String input, as shown in the code above, the output is:
<a href="https://i.stack.imgur.com/zFvic.png" rel="nofollow"><img src="https://i.stack.imgur.com/zFvic.png" alt="enter image description here"></a></p>
<p>But if I enter JSON data with integers:</p>
<p><code>s = '{"92": {"children": [{"87": {"children": [87, 96]}}, {"96": {"children": [90, 105]}}]}}'</code></p>
<p>I get following output: (which is wrong!)</p>
<p><a href="https://i.stack.imgur.com/aTnbF.png" rel="nofollow"><img src="https://i.stack.imgur.com/aTnbF.png" alt="enter image description here"></a></p>
<p>Expected output:
<a href="https://i.stack.imgur.com/MVkyL.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/MVkyL.jpg" alt="enter image description here"></a></p>
<p>What am I doing wrong here? How to solve this issue?</p>
| 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>.format()</code> with <code>print</code> which inserts the value in string independent of maintaing the quotes <code>"</code>. For example:</p>
<pre><code>>>> '{}'.format(1)
'1'
>>> '{}'.format('1')
'1'
</code></pre>
<p>In order to fix this, you may do:</p>
<pre><code>for parent, child in edges:
parent = '"{}"'.format(parent) if isinstance(parent, str) else parent
child = '"{}"'.format(child) if isinstance(child, str) else child
print(' {0} -> {1};'.format(parent, child))
</code></pre>
<p>which prints:</p>
<pre><code>"92" -> "87";
"87" -> 87;
"87" -> 96;
"92" -> "96";
"96" -> 90;
"96" -> 105;
</code></pre>
| 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, so this is pretty advanced to me. EDIT: Thanks to user: 2ps! :D</p>
<pre><code>#Quiz YAY!
#
#Name Removed
#
#Version 1.0
#
score = 0;
modPassword = "200605015"
def modMode(score):
print("Entering Overide Mode");
print("Opening Overide Console")
cmd = input("Enter Command call exit{} to exit: ")
if cmd == "corr":
print("Adding one point")
score=score+1
return(score);
elif cmd== "manScoreChng":
score=int(input("What do want the score to be?"));
elif cmd == 'stop{}':
raise Exception('Quit by User')
score = modMode(score);
print(score);
</code></pre>
| -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 == "corr":
print("Adding one point")
score = score+1
elif cmd == "manScoreChng":
score = int(input("What do want the score to be?"))
elif cmd == 'exit':
raise Exception('Bye!')
return int(score) # MAKE SURE YOU HAVE THIS LINE HERE
</code></pre>
<hr>
<p>To call the <code>modScore</code> command over and over again, use a loop.</p>
<pre><code>try:
while True:
score = modMode(score) # grab the returned value from modMode by using `=`
print(score)
except Exception:
pass
</code></pre>
<p>This will run until the user types in exit.</p>
| 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(zipcode): #LAST BLOCK OF 6 BLOCK BARCODE
zipcode.split()
total=int(zipcode[0])+int(zipcode[1])+int(zipcode[2])+int(zipcode[3])+int(zipcode[4])
if total % 10!=0:
total=total+(10-total%10)
print(correctiondigit(zipcode)) #not working on this yet
def barcode(a):
if a==0:
print("||:::")
elif a==1:
print(":::||")
elif a==2:
print("::|:|")
elif a==3:
print("::||:")
elif a==4:
print(":|::|")
elif a==5:
print(":|:|:")
elif a==6:
print(":||::")
elif a==7:
print("|:::|")
elif a==8:
print("|::|:")
elif a==9:
print("|:|::")
for the_zipcode in s:
print(barcode(the_zipcode))
</code></pre>
| 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(zipcode): #LAST BLOCK OF 6 BLOCK BARCODE
zipcode.split()
total=int(zipcode[0])+int(zipcode[1])+int(zipcode[2])+int(zipcode[3])+int(zipcode[4])
if total % 10!=0:
total=total+(10-total%10)
print(correctiondigit(zipcode)) #not working on this yet
def barcode(a):
if a==0:
print("||:::")
elif a==1:
print(":::||")
elif a==2:
print("::|:|")
elif a==3:
print("::||:")
elif a==4:
print(":|::|")
elif a==5:
print(":|:|:")
elif a==6:
print(":||::")
elif a==7:
print("|:::|")
elif a==8:
print("|::|:")
elif a==9:
print("|:|::")
for the_zipcode in s:
print(barcode(the_zipcode))
</code></pre>
| 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'.split(',') # ['11111', '12345']
</code></pre>
<p>That is almost certainly not what you want, since you're asking the user to input a 5-digit zip code. If you just use the input directly, I think you'll get what you want.</p>
<p>That is:</p>
<pre><code>zipcode=input("What is your 5 digit zipcode?")
# . . .
for digit in zipcode:
print(barcode(digit))
</code></pre>
| 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'),
('5','6'),
('7','8'),
('9','10'))
</code></pre>
<p>Thank you</p>
| -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 is my code :</p>
<pre><code> if results:
for row in results.get('rows'):
rawdata.append(row[0])
else:
print 'No results found'
urllist = [mystring + x for x in rawdata]
for row in urllist[4:8]:
page = urllib2.urlopen(row)
soup = BeautifulSoup(page, 'html.parser')
name_box = soup.find(attrs={'class': 'nb-shares'})
share = name_box.text.strip()
# save the data in tuple
sharelist.append((row,share))
print(sharelist)
</code></pre>
<p>I tried to use this :</p>
<pre><code> except Exception:
pass
</code></pre>
<p>but I don't know where and got some syntax error. I've look at other questions, but cannot find any answers for me. </p>
| 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:
continue
# ...
</code></pre>
| 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
if guess**3 > num:
guess = (guess - delta)
if guess**3 < num:
guess = (guess + delta)
print("Guess:", guess)
</code></pre>
| 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</code> again, which reverses the initial update. In summary, the value of <code>guess</code> is never changed in that loop, and the loop whirls to infinity.</p>
<p>Secondly you want to regularize the <code>delta</code> value (penalize it) as it can be come alarming large as the value of <code>num</code> increases.</p>
<pre><code>num = 100
epsilon = 0.01
guess = num/3.0
while abs(guess**3 - num) >= epsilon:
delta = abs(guess**3 - num)/num
if guess**3 > num:
guess = (guess - delta*epsilon**0.5)
elif guess**3 < num:
guess = (guess + delta*epsilon**0.5)
print("Guess:", guess)
</code></pre>
| 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')"`
</code></pre>
<p>is not very readable.</p>
<p>I would prefer to specify my python code as a multiline string and then execute it.</p>
| 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')"`
</code></pre>
<p>is not very readable.</p>
<p>I would prefer to specify my python code as a multiline string and then execute it.</p>
| 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
END
)
# use the
res="$(python3 -c "$PYTHON_CODE")"
# continue with bash code
echo "$res"
</code></pre>
| 0 | 2016-10-19T23:42:35Z | [
"python",
"bash",
"multiline"
] |