1 + 2 + 34 – 5 + 67 – 8 + 9 = 100

2015-05-29 22:00:00

其实原来是微信推送的东西,第五题比较感兴趣

每个程序员1小时内必须解决的5个编程问题

问题5

编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。例如:1 + 2 + 34 – 5 + 67 – 8 + 9 = 100。

Ps:如果你不知道的话,点击这里,阅读我的解决方案。

CODES = ['+', '-', '']
NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9]


def list_calculate(num):
    if num == 1:
        return [[code] for code in CODES]
    else:
        return [[code] + code_list for code in CODES for code_list in list_calculate(num - 1)]


def calculate_equation(equation):
    result, temp_number, temp_code = 0, NUMBERS[0], '+'
    for i in range(len(equation)):
        the_number = NUMBERS[i + 1]
        if equation[i] is '+' or equation[i] is '-':
            if temp_code is '+':
                result += temp_number
            elif temp_code is '-':
                result -= temp_number
            elif temp_code is None:
                result = the_number
            temp_number, temp_code = the_number, equation[i]
        else:
            temp_number = temp_number * 10 + the_number
    if temp_code is '+':
        result += temp_number
    elif temp_code is '-':
        result -= temp_number
    elif temp_code is '':
        result = result * 10 + temp_number
    return result


def print_equation(equation):
    result = '%s' % NUMBERS[0]
    for i in range(len(equation)):
        if not equation[i] is '':
            result += ' %s ' % equation[i]
        result += '%s' % NUMBERS[i + 1]
    result += ' = %s' % calculate_equation(equation)
    print result


equations = list_calculate(len(NUMBERS) - 1)
for equation in equations:
    if calculate_equation(equation) == 100:
        print_equation(equation)

我现在在想除了穷举还有啥好办法,比如根据位数大致算出一个范围什么的

技术  python 评论 
 

Ubuntu DOSBox 和 金庸群侠传

2015-05-08 22:26:00

DOSBox

金庸群侠传

我突然什么都不想说了……

游戏 
 

今天发现新浪轻居然有rss

2015-04-14 22:34:00
镜头 
 

Feed标准整理RSS & django扩展

2015-04-13 16:11:00

○ 扩展,其实自己继承一个类做起来更好,不过我django1.8是完整代码丢在一起,就直接改本身的Feed了,我觉着本身就是根据标准扩展,也没啥的

√Django 1.8的feedgenerator本来就实现的

2015/8/30更新:因为sae支持了django1.8.3,所以还是用了继承类,好像1.8.3和1.8.0的rss有点区别,item里面添加了comment所以修改之

技术  django
 

简易账本ichartjs

2015-04-08 20:00:00
技术  javascript
 

37.187.248.45又是什么鬼

2015-03-20 00:48:57
技术 
 

永远吐不完槽的sae

2015-03-09 22:53:04

上海备案啊备案啊备案啊备案啊……

python字体啊字体啊字体啊字体啊……

KVDB稳定啊稳定啊稳定啊稳定啊……

django1.8啊1.8啊1.8啊1.8啊……

python3.x啊3.x3.x3.x……(我一个python2.X党为什么要吐这个?)

django form上传图片nginx 504 gateway超时啊超时啊超时啊超时啊……

技术