Skip to content

Instantly share code, notes, and snippets.

@sota1235
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save sota1235/80c4a704d2b68e4f501f to your computer and use it in GitHub Desktop.

Select an option

Save sota1235/80c4a704d2b68e4f501f to your computer and use it in GitHub Desktop.
逆ポーランド記法問題生成 やっつけ仕事
#!/usr/bin/python
# -*- coding: utf-8 -*-
import random
DECIMEL, MINUS = 10, 4 # 小数点/負の数の出現頻度 1/variable name
def randnum(d, m):
num = random.randint(1, 9)
if d: num = randdecimel(num)
if m: num = randminus(num)
return num
def randdecimel(num):
return num if random.randint(0, DECIMEL) != 0 else float(format(random.random(), '.1f')) + float(num)
def randminus(num):
return num if random.randint(0, MINUS) != 0 else num * -1
ans = []
m = eval(input('生成する問題数を入力してください (1 <= M <= 10000)'))
n = eval(input('問題の最大桁数を入力してください (3 <= N <= 100)'))
decimel = True if input("小数点は入れます? Y/n") == "Y" else False
minus = True if input("負の数は入れます? Y/n") == "Y" else False
for i in range(m):
f = random.randint(3, n) # 問題桁数の決定
while f % 2 == 0:
f = random.randint(3, n)
q = [] # 問題
num = [randnum(decimel, minus) for j in range(int(f / 2 + 1))]
obj = [['+', '-', '*', '/'][random.randint(0,3)] for j in range(int(f / 2))]
n1, n2 = 0, 0 # 数字/符号の数
while len(q) < f:
if len(num) == 0:
q += obj # 数字が尽きた場合
break
if n1 - n2 < 2:
q.append(num.pop())
n1 += 1
else:
tmp = random.randint(0, 1)
if tmp == 0:
q.append(num.pop())
n1 += 1
else:
q.append(obj.pop())
n2 += 1
print(" ".join(map(str, q)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment