Skip to content

Instantly share code, notes, and snippets.

@recuraki
Last active January 10, 2024 13:04
Show Gist options
  • Save recuraki/7e5cde9eb3b5a3c2c2895a0a3e77c5db to your computer and use it in GitHub Desktop.
Save recuraki/7e5cde9eb3b5a3c2c2895a0a3e77c5db to your computer and use it in GitHub Desktop.
全俳句データベース
"""
全俳句データベース
https://horicun.moo.jp/contents/haiku/index.html
の機能をPythonで実装します。
haiku.nthHaiku(n): n番目の俳句を表示します。n <= 85 ** (5+7+5)である必要があります。
haiku.HaikuToNth(s): 与えられた5 7 5の俳句sが何番目の俳句かを検索します。
"""
basicChars = "あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわをがぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺぽぁぃぅぇぉゃゅょゎっゐゑーゔん"
haikuLen = 5 + 7 + 5
class haiku(object):
chars = []
charsRev = dict()
charmax = -1
debug = False
def __init__(self, debug=False):
self.debug = debug
self.chars = [x for x in basicChars] #
self.charmax = len(basicChars)
for i in range(self.charmax): self.charsRev[basicChars[i]] = i
if debug: # 5文字ごとにくぎって表示。文字を変えたい時用
for i in range(0, len(self.chars), 5): print(self.chars[i:i+5])
print(self.charsRev)
def base10toN(self, value):
from collections import deque
assert value < self.charmax ** haikuLen
ans = deque()
for _ in range(haikuLen):
ans.appendleft(value % self.charmax)
value //= self.charmax
return list(ans)
def nthHaiku(self, n):
if n <= 0: raise (ValueError, "n must be greater than 0")
n -= 1 # 0-indexedにする
if n >= self.charmax ** haikuLen: raise ValueError
s = "".join([self.chars[x] for x in self.base10toN(n)])
# ここだけ 5 7 5がハードコード
return s[:5] + " " + s[5:5+7] + " " + s[5+7:]
def HaikuToNth(self, s: str):
s = s.replace(" ", "")
s = s.replace(" ", "")
if len(s) != haikuLen: raise ValueError
if not all([x in basicChars for x in s]): raise ValueError
nums = [self.charsRev[x] for x in s]
ans = 0
for i in range(haikuLen):
ans += nums[-1-i] * self.charmax ** i
return ans + 1 # 1-indexedにする
h = haiku()
print(h.nthHaiku(1)) # あああああ あああああああ あああああ
print(h.nthHaiku(86)) # あああああ あああああああ あああいあ
print(h.nthHaiku(85**(5+7+5))) # んんんんん んんんんんんん んんんんん
print(h.nthHaiku(77581285697597397369007992017717)) # さらさらと たけにおとあり よるのゆき
# > https://horicun.moo.jp/contents/haiku/index.html?n=77581285697597397369007992017717
print(h.HaikuToNth("あああああ あああああああ あああああ")) # 1
print(h.HaikuToNth("あああああ あああああああ ああああい")) # 2
print(h.HaikuToNth("んんんんん んんんんんんん んんんんん")) # 631134233006543551770782470703125
print(h.HaikuToNth("ふるいけや かわづとびこむ みずのおと")) # 203973231010201364955964743230760
# > https://horicun.moo.jp/contents/haiku/index.html?n=203973231010201364955964743230760
print(h.HaikuToNth("なつくさや つわものどもが ゆめのあと")) # 149994513986974254541124392927670
# > https://horicun.moo.jp/contents/haiku/index.html?n=149994513986974254541124392927670
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment