原标题:#python# 来做奥数题
来做几道小学奥数题:
红花映绿叶 * 春 = 叶绿映花红
我们热爱科学 * 学 = 好好好好好好
少年早立志向 + 少年早立志向 = 有志何惧少年
学生 + 好学生 + 三好学生 = 2004
数据发生器源码 [data_generator.py]:
# encoding=utf8
import itertools
class DataGenerator(object):
"""
DataGenerator:数生成器
"""
def __init__(self, count=6, digitals=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]):
super(DataGenerator, self).__init__()
self._count = count
self._digitals = digitals
def get_digitals(self):
return self._digitals
def generate_numbers(self):
"""
获取定长的由数字组成的数,例如:
_count = 6, 返回所有的可能数字组合,对应的数,对应的逆序数
5 -> [([1, 2, 3, 4, 5], 12345, 54321), [1, 2, 3, 4, 6], 12346, 64321), ...]
"""
all = list(itertools.permutations(self._digitals, self._count))
return [(x,
self._generate_numbers_from_digit_list(x),
self._generate_numbers_from_digit_list(x, True))
for x in all if len(set(x)) == self._count and x[-1] != 0]
def _generate_numbers_from_digit_list(self, digit_list, revert=False):
"""
由一个数字列表返回对应的数,例如:
[1, 2, 3, 4, 5], False -> 12345
[1, 2, 3, 4, 5], True -> 54321
"""
return sum([digit * 10**index for index, digit in enumerate(digit_list if not revert else digit_list[::-1])])
class NumberAttr(object):
"""
NumberAttr:数属性
"""
def __init__(self, number):
super(NumberAttr, self).__init__()
self._number = number
def get_digit_by_pos(self, pos):
"""
获取数某个位置上的数字
1234, 1 -> 4
4321, 1 -> 1
"""
number = self._number
while pos:
(div, mod) = divmod(number, 10)
number = div
pos -= 1
return mod
def get_number_bits(self):
"""
获取数共有多少位
123 -> 3
4321 -> 4
"""
number = self._number
count = 0
while number:
(div, mod) = divmod(number, 10)
number = div
count += 1
return count
责任编辑: