Example #1
0
def edit_ad(url):
    room = Room.query.filter_by(urlname=url).first()
    if not room and room.user == g.user:
        abort(404)
    if room.dead or get_days_ago(room.created_at) > OLD_DAYS.days:
        abort(404)
    occupied = Occupied.query.filter_by(space=room.occupieds).order_by("created_at").first()
    if occupied and get_days_ago(occupied.created_at) > OCCUPIED_DAYS.days:
        abort(404)
    if room.is_available:
        form = AvailableAdForm()
    else:
        form = WantedAdForm()
    form.starting.flags.is_date = True
    if request.method == "GET":
        form.process(obj=room)
        if room.is_available:
            form.room_pref.data = factorize(room.room_pref)
        else:
            form.room_type.data = factorize(room.room_type)
        form.email.data = g.user.email
    elif form.validate_on_submit():
        if room.is_available:
            form.room_pref.data = product(form.room_pref.data)
        else:
            form.room_type.data = product(form.room_type.data)
        form.populate_obj(room)
        db.session.commit()
        return redirect(url_for("view_ad", url=room.urlname))
    return render_template("autoform.html", form=form, title="Edit advertisement", submit="Save")
Example #2
0
def is_sq_free(n, k):
    """Checks whether C(n, k) is square free)"""
    from collections import Counter
    c = Counter()
    for i in range(1, k + 1):
        c += Counter(dict(factorize(n - i + 1)))
        c -= Counter(dict(factorize(i)))
    return all(v == 1 for v in c.values())
Example #3
0
 def __init__(self, stims, psth_data,tres=15):
     self.stims = stims
     self.psth_data = psth_data
     self.tres = tres
     self.STA = reverse_correlation(stims,psth_data,tres,normalize="pseudo_inverse",smooth=1)
     self.Sfact, self.Tfact = utils.factorize(self.STA)
     self.channels, self.sres = self.Sfact.shape
Example #4
0
def number_of_factors(n):
    prime_factors = factorize(n) 
    grouped_factors = [list(g) for k, g in groupby(prime_factors)]
    count = 1
    for factor_group in grouped_factors:
        count *= len(factor_group) + 1
    return count
Example #5
0
def M(n):
    fs = [p**pp for p, pp in factorize(n)]

    f2 = [n // f * modinv(n // f, f) % n for f in fs]

    ans = 0
    for i in range(2**len(fs)):
        cur = sum(f2[j] for j in range(len(fs)) if i & (1 << j))
        ans = max(ans, cur % n)

    return ans
Example #6
0
from utils import factorize


def product(seq):
    return reduce(lambda x, y: x * y, seq, 1)


limit = 10**5
pos = 10**4

radicals = []

for i in range(1, limit + 1):
    radical = product(p for p, _ in factorize(i))
    radicals.append((radical, i))

radicals.sort()
print radicals[pos - 1][1]
Example #7
0
from utils import factorize, product

limit = 10**6

count = 0
for n in range(8, limit + 1, 4):
    k = n // 4
    l = product(p + 1 for _, p in factorize(k)) // 2

    if l <= 10:
        count += 1

print count
Example #8
0
from utils import factorize, chinese
from itertools import product

n = 91


def roots(n):
    res = []
    for i in range(n):
        if i**3 % n == 1:
            res.append(i)
    return res


rems = []
mods = []
for p, pow in factorize(n):
    rems.append(roots(p**pow))
    mods.append(p**pow)

ans = set()
for p in product(*rems):
    ans.add(chinese(list(p), mods))

print(sum(ans))
Example #9
0
from utils import factorize, product

for n in xrange(2, 1000000):
    c = product(2 * p + 1 for prime, p in factorize(n))
    if c > 1999:
        print n
        break
Example #10
0
#!/usr/bin/env python2
# coding: utf-8


from collections import Counter
from utils import factorize


def triangle(n):
    return (n * (n + 1)) / 2

i = 1
while True:
    current = triangle(i)
    prime_factors = factorize(current)
    count = Counter(prime_factors)
    num_divisors = sum(count.values())

    if num_divisors >= 500:
        print current
        break
    i += 1
Example #11
0
def combine(dataFrame):
    all = pd.DataFrame(index=dataFrame.index)

    all["LotFrontage"] = dataFrame["LotFrontage"]
    for key, group in lot_frontage_by_neighborhood:
        idx = (dataFrame["Neighborhood"]
               == key) & (dataFrame["LotFrontage"].isnull())
        all.loc[idx, "LotFrontage"] = group.median()

    all["LotArea"] = dataFrame["LotArea"]

    all["MasVnrArea"] = dataFrame["MasVnrArea"]
    all["MasVnrArea"].fillna(0, inplace=True)

    all["BsmtFinSF1"] = dataFrame["BsmtFinSF1"]
    all["BsmtFinSF1"].fillna(0, inplace=True)

    all["BsmtFinSF2"] = dataFrame["BsmtFinSF2"]
    all["BsmtFinSF2"].fillna(0, inplace=True)

    all["BsmtUnfSF"] = dataFrame["BsmtUnfSF"]
    all["BsmtUnfSF"].fillna(0, inplace=True)

    all["TotalBsmtSF"] = dataFrame["TotalBsmtSF"]
    all["TotalBsmtSF"].fillna(0, inplace=True)

    all["1stFlrSF"] = dataFrame["1stFlrSF"]
    all["2ndFlrSF"] = dataFrame["2ndFlrSF"]
    all["GrLivArea"] = dataFrame["GrLivArea"]

    all["GarageArea"] = dataFrame["GarageArea"]
    all["GarageArea"].fillna(0, inplace=True)

    all["WoodDeckSF"] = dataFrame["WoodDeckSF"]
    all["OpenPorchSF"] = dataFrame["OpenPorchSF"]
    all["EnclosedPorch"] = dataFrame["EnclosedPorch"]
    all["3SsnPorch"] = dataFrame["3SsnPorch"]
    all["ScreenPorch"] = dataFrame["ScreenPorch"]

    all["BsmtFullBath"] = dataFrame["BsmtFullBath"]
    all["BsmtFullBath"].fillna(0, inplace=True)

    all["BsmtHalfBath"] = dataFrame["BsmtHalfBath"]
    all["BsmtHalfBath"].fillna(0, inplace=True)

    all["FullBath"] = dataFrame["FullBath"]
    all["HalfBath"] = dataFrame["HalfBath"]
    all["BedroomAbvGr"] = dataFrame["BedroomAbvGr"]
    all["KitchenAbvGr"] = dataFrame["KitchenAbvGr"]
    all["TotRmsAbvGrd"] = dataFrame["TotRmsAbvGrd"]
    all["Fireplaces"] = dataFrame["Fireplaces"]

    all["GarageCars"] = dataFrame["GarageCars"]
    all["GarageCars"].fillna(0, inplace=True)

    all["CentralAir"] = (dataFrame["CentralAir"] == "Y") * 1.0

    all["OverallQual"] = dataFrame["OverallQual"]
    all["OverallCond"] = dataFrame["OverallCond"]

    # Quality measurements are stored as text but we can convert them to
    # numbers where a higher number means higher quality.

    qual_dict = {None: 0, "Po": 1, "Fa": 2, "TA": 3, "Gd": 4, "Ex": 5}
    all["ExterQual"] = dataFrame["ExterQual"].map(qual_dict).astype(int)
    all["ExterCond"] = dataFrame["ExterCond"].map(qual_dict).astype(int)
    all["BsmtQual"] = dataFrame["BsmtQual"].map(qual_dict).astype(int)
    all["BsmtCond"] = dataFrame["BsmtCond"].map(qual_dict).astype(int)
    all["HeatingQC"] = dataFrame["HeatingQC"].map(qual_dict).astype(int)
    all["KitchenQual"] = dataFrame["KitchenQual"].map(qual_dict).astype(int)
    all["FireplaceQu"] = dataFrame["FireplaceQu"].map(qual_dict).astype(int)
    all["GarageQual"] = dataFrame["GarageQual"].map(qual_dict).astype(int)
    all["GarageCond"] = dataFrame["GarageCond"].map(qual_dict).astype(int)

    all["BsmtExposure"] = dataFrame["BsmtExposure"].map({
        None: 0,
        "No": 1,
        "Mn": 2,
        "Av": 3,
        "Gd": 4
    }).astype(int)

    bsmt_fin_dict = {
        None: 0,
        "Unf": 1,
        "LwQ": 2,
        "Rec": 3,
        "BLQ": 4,
        "ALQ": 5,
        "GLQ": 6
    }
    all["BsmtFinType1"] = dataFrame["BsmtFinType1"].map(bsmt_fin_dict).astype(
        int)
    all["BsmtFinType2"] = dataFrame["BsmtFinType2"].map(bsmt_fin_dict).astype(
        int)

    all["Functional"] = dataFrame["Functional"].map({
        None: 0,
        "Sal": 1,
        "Sev": 2,
        "Maj2": 3,
        "Maj1": 4,
        "Mod": 5,
        "Min2": 6,
        "Min1": 7,
        "Typ": 8
    }).astype(int)

    all["GarageFinish"] = dataFrame["GarageFinish"].map({
        None: 0,
        "Unf": 1,
        "RFn": 2,
        "Fin": 3
    }).astype(int)

    all["Fence"] = dataFrame["Fence"].map({
        None: 0,
        "MnWw": 1,
        "GdWo": 2,
        "MnPrv": 3,
        "GdPrv": 4
    }).astype(int)

    all["YearBuilt"] = dataFrame["YearBuilt"]
    all["YearRemodAdd"] = dataFrame["YearRemodAdd"]

    all["GarageYrBlt"] = dataFrame["GarageYrBlt"]
    all["GarageYrBlt"].fillna(0.0, inplace=True)

    all["MoSold"] = dataFrame["MoSold"]
    all["YrSold"] = dataFrame["YrSold"]

    all["LowQualFinSF"] = dataFrame["LowQualFinSF"]
    all["MiscVal"] = dataFrame["MiscVal"]

    all["PoolQC"] = dataFrame["PoolQC"].map(qual_dict).astype(int)

    all["PoolArea"] = dataFrame["PoolArea"]
    all["PoolArea"].fillna(0, inplace=True)

    # Add categorical features as numbers too. It seems to help a bit.
    factorize(dataFrame, all, "MSSubClass")
    factorize(dataFrame, all, "MSZoning", "RL")
    factorize(dataFrame, all, "LotConfig")
    factorize(dataFrame, all, "Neighborhood")
    factorize(dataFrame, all, "Condition1")
    factorize(dataFrame, all, "BldgType")
    factorize(dataFrame, all, "HouseStyle")
    factorize(dataFrame, all, "RoofStyle")
    factorize(dataFrame, all, "Exterior1st", "Other")
    factorize(dataFrame, all, "Exterior2nd", "Other")
    factorize(dataFrame, all, "MasVnrType", "None")
    factorize(dataFrame, all, "Foundation")
    factorize(dataFrame, all, "SaleType", "Oth")
    factorize(dataFrame, all, "SaleCondition")

    # IR2 and IR3 don't appear that often, so just make a distinction
    # between regular and irregular.
    all["IsRegularLotShape"] = (dataFrame["LotShape"] == "Reg") * 1

    # Most properties are level; bin the other possibilities together
    # as "not level".
    all["IsLandLevel"] = (dataFrame["LandContour"] == "Lvl") * 1

    # Most land slopes are gentle; treat the others as "not gentle".
    all["IsLandSlopeGentle"] = (dataFrame["LandSlope"] == "Gtl") * 1

    # Most properties use standard circuit breakers.
    all["IsElectricalSBrkr"] = (dataFrame["Electrical"] == "SBrkr") * 1

    # About 2/3rd have an attached garage.
    all["IsGarageDetached"] = (dataFrame["GarageType"] == "Detchd") * 1

    # Most have a paved drive. Treat dirt/gravel and partial pavement
    # as "not paved".
    all["IsPavedDrive"] = (dataFrame["PavedDrive"] == "Y") * 1

    # The only interesting "misc. feature" is the presence of a shed.
    all["HasShed"] = (dataFrame["MiscFeature"] == "Shed") * 1.

    # If YearRemodAdd != YearBuilt, then a remodeling took place at some point.
    all["Remodeled"] = (all["YearRemodAdd"] != all["YearBuilt"]) * 1

    # Did a remodeling happen in the year the house was sold?
    all["RecentRemodel"] = (all["YearRemodAdd"] == all["YrSold"]) * 1

    # Was this house sold in the year it was built?
    all["VeryNewHouse"] = (all["YearBuilt"] == all["YrSold"]) * 1

    all["Has2ndFloor"] = (all["2ndFlrSF"] == 0) * 1
    all["HasMasVnr"] = (all["MasVnrArea"] == 0) * 1
    all["HasWoodDeck"] = (all["WoodDeckSF"] == 0) * 1
    all["HasOpenPorch"] = (all["OpenPorchSF"] == 0) * 1
    all["HasEnclosedPorch"] = (all["EnclosedPorch"] == 0) * 1
    all["Has3SsnPorch"] = (all["3SsnPorch"] == 0) * 1
    all["HasScreenPorch"] = (all["ScreenPorch"] == 0) * 1

    # Months with the largest number of deals may be significant.
    all["HighSeason"] = dataFrame["MoSold"].replace({
        1: 0,
        2: 0,
        3: 0,
        4: 1,
        5: 1,
        6: 1,
        7: 1,
        8: 0,
        9: 0,
        10: 0,
        11: 0,
        12: 0
    })

    all["NewerDwelling"] = dataFrame["MSSubClass"].replace({
        20: 1,
        30: 0,
        40: 0,
        45: 0,
        50: 0,
        60: 1,
        70: 0,
        75: 0,
        80: 0,
        85: 0,
        90: 0,
        120: 1,
        150: 0,
        160: 0,
        180: 0,
        190: 0
    })

    all.loc[dataFrame.Neighborhood == 'NridgHt', "Neighborhood_Good"] = 1
    all.loc[dataFrame.Neighborhood == 'Crawfor', "Neighborhood_Good"] = 1
    all.loc[dataFrame.Neighborhood == 'StoneBr', "Neighborhood_Good"] = 1
    all.loc[dataFrame.Neighborhood == 'Somerst', "Neighborhood_Good"] = 1
    all.loc[dataFrame.Neighborhood == 'NoRidge', "Neighborhood_Good"] = 1
    all["Neighborhood_Good"].fillna(0, inplace=True)

    all["SaleCondition_PriceDown"] = dataFrame.SaleCondition.replace({
        'Abnorml':
        1,
        'Alloca':
        1,
        'AdjLand':
        1,
        'Family':
        1,
        'Normal':
        0,
        'Partial':
        0
    })

    # House completed before sale or not
    all["BoughtOffPlan"] = dataFrame.SaleCondition.replace({
        "Abnorml": 0,
        "Alloca": 0,
        "AdjLand": 0,
        "Family": 0,
        "Normal": 0,
        "Partial": 1
    })

    all["BadHeating"] = dataFrame.HeatingQC.replace({
        'Ex': 0,
        'Gd': 0,
        'TA': 0,
        'Fa': 1,
        'Po': 1
    })

    area_cols = [
        'LotFrontage', 'LotArea', 'MasVnrArea', 'BsmtFinSF1', 'BsmtFinSF2',
        'BsmtUnfSF', 'TotalBsmtSF', '1stFlrSF', '2ndFlrSF', 'GrLivArea',
        'GarageArea', 'WoodDeckSF', 'OpenPorchSF', 'EnclosedPorch',
        '3SsnPorch', 'ScreenPorch', 'LowQualFinSF', 'PoolArea'
    ]
    all["TotalArea"] = all[area_cols].sum(axis=1)

    all["TotalArea1st2nd"] = all["1stFlrSF"] + all["2ndFlrSF"]

    all["Age"] = 2010 - all["YearBuilt"]
    all["TimeSinceSold"] = 2010 - all["YrSold"]

    all["SeasonSold"] = all["MoSold"].map({
        12: 0,
        1: 0,
        2: 0,
        3: 1,
        4: 1,
        5: 1,
        6: 2,
        7: 2,
        8: 2,
        9: 3,
        10: 3,
        11: 3
    }).astype(int)

    all["YearsSinceRemodel"] = all["YrSold"] - all["YearRemodAdd"]

    # Simplifications of existing features into bad/average/good.
    all["SimplOverallQual"] = all.OverallQual.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2,
        6: 2,
        7: 3,
        8: 3,
        9: 3,
        10: 3
    })
    all["SimplOverallCond"] = all.OverallCond.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2,
        6: 2,
        7: 3,
        8: 3,
        9: 3,
        10: 3
    })
    all["SimplPoolQC"] = all.PoolQC.replace({1: 1, 2: 1, 3: 2, 4: 2})
    all["SimplGarageCond"] = all.GarageCond.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2
    })
    all["SimplGarageQual"] = all.GarageQual.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2
    })
    all["SimplFireplaceQu"] = all.FireplaceQu.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2
    })
    all["SimplFireplaceQu"] = all.FireplaceQu.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2
    })
    all["SimplFunctional"] = all.Functional.replace({
        1: 1,
        2: 1,
        3: 2,
        4: 2,
        5: 3,
        6: 3,
        7: 3,
        8: 4
    })
    all["SimplKitchenQual"] = all.KitchenQual.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2
    })
    all["SimplHeatingQC"] = all.HeatingQC.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2
    })
    all["SimplBsmtFinType1"] = all.BsmtFinType1.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2,
        6: 2
    })
    all["SimplBsmtFinType2"] = all.BsmtFinType2.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2,
        6: 2
    })
    all["SimplBsmtCond"] = all.BsmtCond.replace({1: 1, 2: 1, 3: 1, 4: 2, 5: 2})
    all["SimplBsmtQual"] = all.BsmtQual.replace({1: 1, 2: 1, 3: 1, 4: 2, 5: 2})
    all["SimplExterCond"] = all.ExterCond.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2
    })
    all["SimplExterQual"] = all.ExterQual.replace({
        1: 1,
        2: 1,
        3: 1,
        4: 2,
        5: 2
    })

    # Bin by neighborhood (a little arbitrarily). Values were computed by:
    # train_dataFrame["SalePrice"].groupby(train_dataFrame["Neighborhood"]).median().sort_values()
    neighborhood_map = {
        "MeadowV": 0,  # 88000
        "IDOTRR": 1,  # 103000
        "BrDale": 1,  # 106000
        "OldTown": 1,  # 119000
        "Edwards": 1,  # 119500
        "BrkSide": 1,  # 124300
        "Sawyer": 1,  # 135000
        "Blueste": 1,  # 137500
        "SWISU": 2,  # 139500
        "NAmes": 2,  # 140000
        "NPkVill": 2,  # 146000
        "Mitchel": 2,  # 153500
        "SawyerW": 2,  # 179900
        "Gilbert": 2,  # 181000
        "NWAmes": 2,  # 182900
        "Blmngtn": 2,  # 191000
        "CollgCr": 2,  # 197200
        "ClearCr": 3,  # 200250
        "Crawfor": 3,  # 200624
        "Veenker": 3,  # 218000
        "Somerst": 3,  # 225500
        "Timber": 3,  # 228475
        "StoneBr": 4,  # 278000
        "NoRidge": 4,  # 290000
        "NridgHt": 4,  # 315000
    }

    all["NeighborhoodBin"] = dataFrame["Neighborhood"].map(neighborhood_map)
    return all
Example #12
0
def largest_factor(number):
    return factorize(number)[-1]
Example #13
0
from utils import factorize
from math import e, ceil, log
from fractions import Fraction
from decimal import Decimal

limit = 10000
res = 0

for n in range(5, limit+1):
    a = int(n/e)
    b = int(ceil(n/e))

    k = max([a, b], key=lambda x: x * log(1.0*n/x))
    denom = Fraction(n, k).denominator

    if not all(p in (2, 5) for p,_ in factorize(denom)):
        res += n
    else:
        res -= n

print res

from utils import factorize
from array import array

def trianglenum(n):
	return n*(n+1)/2

i = 1
factors = array('L')
while len(factors) <= 500:
	i += 1
	factors = factorize(trianglenum(i))
print trianglenum(i)
Example #15
0
def largestPrimeFactor( num ):
    factors = factorize( num, primes )
    return max( factors )
Example #16
0
def ss(xs):
    res = defaultdict(int)
    for i in range(len(xs) + 1):
        for comb in combinations(xs, i):
            s = sum(comb)
            if s <= target:
                res[s] += 1
    return res


t = 81
excluded = [16, 27, 32, 48, 54, 64, 65, 80]
fs = [
    Fraction(1, x)**2 for x in range(2, t)
    if x not in excluded and all(p in [2, 3, 5, 7, 13]
                                 for p, _ in factorize(x))
]

h = len(fs) // 2

left = fs[:h]
right = fs[h:]

ss1 = ss(left)
ss2 = ss(right)

res = 0
for k, v in ss1.items():
    res += v * ss2[target - k]

print(res)