Skip to content

Instantly share code, notes, and snippets.

@cocodrips
cocodrips / prime_decomposition.py
Last active August 29, 2015 13:55
素因数分解
def prime_decomposition(n):
i = 2
table = []
while i * i <= n:
while n % i == 0:
n /= i
table.append(i)
i += 1
if n > 1:
table.append(n)
@cocodrips
cocodrips / is_prime.py
Last active August 29, 2015 13:55
素数判定
def is_prime(n):
i = 2
while i * i <=n:
if n % i == 0:
return False
i += 1
return True
@cocodrips
cocodrips / prime_table.py
Last active August 29, 2015 13:55
素数テーブル
def prime_table(n):
list = [True for _ in xrange(n + 1)]
i = 2
while i * i <= n:
if list[i]:
j = i + i
while j <= n:
list[j] = False
j += i
i += 1
@cocodrips
cocodrips / projecteuler18.py
Last active August 29, 2015 13:56
projecteuler18
def maximum_path(array, n):
dp = [[0 for __ in xrange(n)] for _ in xrange(n)]
dp[0][0] = array[0][0]
for i in xrange(1, n):
for j in xrange(i + 1):
if j == 0:
dp[i][j] = array[i][j] + dp[i - 1][j]
elif j == i:
dp[i][j] = array[i][j] + dp[i - 1][j - 1]
def memoize(f):
memo = {}
def inner(v):
if v <0: return memo
if not v in memo:
memo[v] = f(v)
return memo[v]
return inner
@cocodrips
cocodrips / gcd.py
Created March 5, 2014 01:51
ゆ〜ぐりっど
def gcd(a, b):
while b:
a, b = b, a % b
return a
@cocodrips
cocodrips / lcm.py
Created March 5, 2014 01:51
最小公倍数
def lcm(a, b):
return a * b // gcd (a, b)
@cocodrips
cocodrips / code.py
Created March 20, 2014 10:01
unicode/ str
# -*- coding: utf-8 -*-
uj = u'こんにちは'
ue = u'Hello'
sj = 'こんにちは'
se = 'Hello'
print ue == se # True
print uj == sj # False Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
print sj.decode('utf-8'), type(sj.decode('utf-8')) #こんにちは
@cocodrips
cocodrips / Clustering.py
Last active August 29, 2015 13:57
文字コードこわい
class Clustering:
def _analyzer(self, text):
ret = []
tagger = MeCab.Tagger("-Ochasen")
if type(text) == UnicodeType:
text = text.encode("utf-8")
node = tagger.parseToNode(text)
while node.next:
basic = unicode(node.feature.split(',')[-3], 'utf-8')
if basic != u"*":
@cocodrips
cocodrips / clustering.py
Created March 20, 2014 11:19
文章のクラスタリング
# -*- coding: utf-8 -*-
import MeCab
import numpy as np
from types import *
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans, MiniBatchKMeans
from sklearn.decomposition import TruncatedSVD
from sklearn.preprocessing import Normalizer