Decimal part of a number in Python
I have the following program
def F_inf(a,b):
x1=a.numerator/a.denominator
x2=b.numerator/b.denominator
if x1<x2:
print "a<b"
elif x1>x2:
print "a>b"
else: print "a=b"
a=Fraction(10,4)
b=Fraction(10,4)
F_inf(a, b)
When I execute it,x1 receive just the integer value of the fraction, for exemple if I have to compute 2/4 x1 is equal to 0 not 0.5. What should I do ? Thanks
1 answer

It sounds like you're using Python2. The best solution would be to switch to Python 3 (not just because of the division but because "Python 2.x is legacy, Python 3.x is the present and future of the language").
Other than that you have a couple of choices.
from __future__ import division # include ^ as the first line in your file to use float division by default
or
a = 1 b = 2 c = a / (1.0*b) # multiplying by 1.0 forces the right side of the division to be a float #c == 0.5 here
See also questions close to this topic

Pandas Dataframe groupby describe 8x ~slower than computing separatly
The following code summarizes numeric data using two different approaches.
The first approach uses the Dataframe().describe() and passes some specific extra percentiles.
The second approach separately computes the summary stats (mean, std, N), stacks it, computes the same quantiles, then appends the two and sorts by the index so the result is essentially the same as the first approach.
There are some minor naming differences that we can clean up afterword's and since the summarized data is small, that is very fast.
Turns out that using the describe function was about 8x slower in this example.
I am looking for reasons why and perhaps suggestions on any other approaches that may speed this up even more (filters, groups, values) are all passed in from UI to a tornado service  so speed is important, as the user is waiting for results, and the data can be even larger that this example.
import pandas as pd import numpy as np from datetime import datetime def make_data (n): ts = datetime.now().timestamp() + abs(np.random.normal(60, 30, n)).cumsum() df = pd.DataFrame({ 'c1': np.random.choice(list('ABCDEFGH'), n), 'c2': np.random.choice(list('ABCDEFGH'), n), 'c3': np.random.choice(list('ABCDEFGH'), n), 't1': np.random.randint(1, 20, n), 't2': pd.to_datetime(ts, unit='s'), 'x1': np.random.randn(n), 'x2': np.random.randn(n), 'x3': np.random.randn(n) }) return df def summarize_numeric_1 (df, mask, groups, values, quantiles): dfg = df[mask].groupby(groups)[values] return dfg.describe(percentiles = quantiles).stack() def summarize_numeric_2 (df, filt, groups, values, quantiles): dfg = df[mask].groupby(groups)[values] dfg_stats = dfg.agg([np.mean, np.std, len]).stack() dfg_quantiles = dfg.quantile(all_quantiles) return dfg_stats.append(dfg_quantiles).sort_index() %time df = make_data(1000000) groups = ['c1', 'c2', 't1'] mask = df['c3'].eq('H') & df['c1'].eq('A') values = ['x1', 'x3'] base_quantiles = [0, .5, 1] extd_quantiles = [0.25, 0.75, 0.9] all_quantiles = base_quantiles + extd_quantiles %timeit summarize_numeric_1(df, mask, groups, values, extd_quantiles) %timeit summarize_numeric_2(df, mask, groups, values, all_quantiles)
The timings on my PC for this are:
Using describe: 873 ms ± 8.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Using two step method: 105 ms ± 490 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
All inputs welcome!

Odd Nested Loop Doesn't Break Properly (Python 3.x)
The following code should print multiple lines of
1 2 3
mixed with lines of
0
However, what it actually prints is multiple lines of
1 1 1 1 3
mixed with lines of
0
Code:
boxes = [] for y in range(len(hmap)): for x in range(len(hmap[y])): w = 4 h = 4 minh = hmap[y][x] maxh = hmap[y][x] htemp = h while True: if y + htemp > len(hmap): break passes = False wtemp = w while True: if x + wtemp > len(hmap[y]): break for c in range(x, x+wtemp): for r in range(y, y+htemp): minh = min(minh,hmap[c][r]) maxh = max(maxh,hmap[c][r]) if maxh  minh > v: print('1') break else: print('2') break else: print('3') break print('0') passes = True wtemp += 1 if passes: boxes.append([x,y,wtemp1,htemp]) htemp += 1 if not passes: break
hmap
is a 2D array of float values that is passed to the function this code is in.
This segment of code is supposed to generate a series of rectangles for other (irrelevant) parts of code to use later on. Rectangles that "pass" (min/max values don't have a difference greater than
v
) cause0
to be printed. Rectangles that don't "pass" should cause
1 2 3
to be printed as the nested
for
andwhile
loops break. Why doesn't it work? 
Can someone help me turn this for loop into a map?
I'm trying to make my code more efficient. I'm not super familiar with maps. I can do simple ones but I'm having trouble wrapping my head around this one
def mate(self, parent1, parent2): length = parent1.size parent1 *= 1e6 parent2 *= 1e6 parent1 = parent1.astype(int) parent2 = parent2.astype(int) child1 = [] child2 = [] for i in range(length): hold1 = parent1[i] hold2 = parent2[i] hold1 = np.binary_repr(hold1, 30) hold2 = np.binary_repr(hold2, 30) pivot = np.random.randint(0, length) childGene1 = hold1[:pivot] + hold2[pivot:] childGene2 = hold2[:pivot] + hold1[pivot:] childGene1 = int(childGene1, 2) / 1e6 childGene2 = int(childGene2, 2) / 1e6 child1.append(childGene1) child2.append(childGene2) return [child1, child2]
It's a mating function I made for a genetic algorithm. How should I go about turning this into a map?

Django Set a Formula for field
I want to set manual arithmetic formula of a field in a model, the formula changes from object to object of the model and is set by some user and sets it depending on the foreign model name.
class Strategy(models.Model): name = models.CharField(max_length=30, unique=True) class Line(models.Model): strategy = models.ForeignKey(Strategy,on_delete=models.CASCADE) startvalue = models.FloatField(default=0) endvalue = models.FloatField(null=True,blank=True) target = models.FloatField(default=0) alpha = models.FloatField(default=0)
So, Here there will be many strategies, And for each strategy I want superuser to map an arithmetic formula for alpha in terms of startvalue, endvalue, target
for example if a strategy is
s1 then alpha = 100*(startvalue+endvalue*target)
s2 then alpha = startvalueendvalue*target
Like this, the superuser needs to set the formula of alpha for a strategy through GUI so that all Lines with that strategy have that formula for alpha.
How to implement this? Please help me, I'm stuck here for more than two days.

Python 2 :Tk inter bind function on page to start a routine
as the title states, my bind function does not dowhat it should do
code can be found here: https://github.com/Acrasy/fotobox/blob/master/gui01.py
i want the bind function on my main window to start a routine, but i can't get the page even to be clickableany help is much appreciated

matplotlib setting on Anaconda 2 5.2.0 64 bit
I am using Jupiter Notebook with the following configuration for matplotlib
import numpy as np import matplotlib.pyplot as plt %matplotlib notebook plt.rcParams [ 'figure.figsize' ] = ( 12 , 7)
and with a 24'' monitor since long time.
I use the line of code "%matplotlib notebook" because it generates an interactive plot interface with the mouse coordinates reported on the right bottom of the interface itself.
On the other hand, the last line of code sets the plot at its maximum sizes without getting over the monitor itself (which requires the use of scrollbars inside jupyter and/or a scroll over the browser page).
Today I've updated my Anaconda distribution from Anaconda2 4.2.0 64bit to Anaconda 2 5.2.0 64 bit, my previous settings do not satisfy me any more and I would like you to help me with this issue.
According with the former Anaconda distribution, the code
x = np.arange(3, 3, 0.01) y = np.sin( np.pi*x )/(np.pi) plt.figure() plt.plot(x, y) plt.show()
should provide a plot with the right size for my monitor. What I get on the new Anaconda distribution is reported in the following picture
The problem is not about the size of the plot itself, which still can be adjusted via the 'figure.figsize' setting, but with the position of the coordinates that are really far away from the graph. It looks like there is a huge amount of unused space both at the right side and the bottom side of the plot itself. Would you help me to figure out a better setting for my matplotlib on jupyter notebook, please?