Created
March 9, 2020 12:05
-
-
Save Joseph-Bake/3b540cf4736b14e50e781b50b576091c to your computer and use it in GitHub Desktop.
Zig-Zag Number ねげろんさんのを改造
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import itertools | |
import numpy | |
def getZigZagNumber(num): | |
# 0, 1, 2番目のZig-Zag Numberは1と定義 | |
if (num == 0) or (num == 1) or (num == 2): | |
return 1 | |
else: | |
alterPerm = 0 | |
for perm in itertools.permutations(list(range(num))): | |
frontSign = 0 | |
backSign = 0 | |
# i番目とi + 1番目の差をとって符号を取得し, | |
# 前ステップで取得した i - 1番目とi番目の差の符号との積をとる | |
for i in range(len(perm) - 1): | |
# 最初は0番目と1番目の差の符号のみを取得する | |
# 0番目と1番目の差の符号が正であれば交代順列の定義に反するので終了 | |
# 0番目と1番目の差の符号が負であれば次のステップへ | |
if i == 0: | |
frontSign = numpy.sign(perm[i] - perm[i + 1]) | |
if frontSign == 1: | |
break | |
continue | |
backSign = numpy.sign(perm[i] - perm[i + 1]) | |
# 積が1であれば符号が反転しておらず交代順列の定義に反するので終了 | |
if frontSign * backSign == 1: | |
break | |
# 積が-1であれば符号が反転しているので次のステップへ進む | |
else: | |
frontSign = backSign | |
if i == len(perm) - 2: | |
# 交代順列であれば配列に格納 | |
alterPerm += 1 | |
# 配列の長さ=交代順列の総数を返す | |
return alterPerm | |
# 求めたいZig-Zag Numberの長さ | |
length = 11 | |
for i in range(length): | |
print('Alt_', i , ':', getZigZagNumber(i)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment