每个程序员1小时内必须解决的5个编程问题之难题
2015-05-13 14:02
477 查看
昨天看到一篇文章说,软件开发人员应一小时完成的5道题,其中第5道题,还是比较难的。看了一下作者的原来解题思路,就是采用治减法,这是一类问题的算法题,如果没有接触过,确实有点难度。作者提供了J***A的源码,由于我没有J***A的运行环境,不能执行,只好改为Python的方式,顺便熟悉Python,运行了一下,递归的方法是简单,并且容易理解它,但如果自己没有去写一下,调试一下,理解起来还是有困难的。
代码如下:
运行结果如下:
>>>
1+2+3-4+5+6+78+9
1+2+34-5+67-8+9
1+23-4+5+6+78-9
1+23-4+56+7+8+9
12+3+4+5-6-7+89
12+3-4+5+67+8+9
12-3-4+5-6+7+89
123+4-5+67-89
123+45-67+8-9
123-4-5-6-7+8-9
123-45-67+89
>>>
相关文章的连接:
每个程序员1小时内必须解决的5个编程问题 http://www.codeceo.com/article/5-problems-programmer-1-hour.html https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour https://blog.svpino.com/2015/05/08/solution-to-problem-5-and-some-other-thoughts-about-this-type-of-questions
蔡军生 QQ:9073204 深圳
代码如下:
#python 3.4.3 win7 #问题5 #编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序, #并输出所有的可能性。例如:1 + 2 + 34 – 5 + 67 – 8 + 9 = 100。 #数字序列 NumList = [x for x in range(1,10)] #目标值 TARGET_SUM = 100 #添加一个数字到表达式字符串 def add(digit, sign, branches): tempL = branches #采用临时列表,防止原地修改 for x in range(len(tempL)): tempL[x] = str(digit) + sign + tempL[x] return tempL #递归函数实现分治算法。 def fun(sum, number, index): digit = abs(number) % 10 #递归跳出条件 if index >= len(NumList): if sum == number: return [str(digit)] return [] #三个按算法要求的分支递归 branch1 = fun(sum - number, NumList[index], index + 1) branch2 = fun(sum - number, -NumList[index], index + 1) conNum = 0 if number < 0: conNum = number * 10 - NumList[index] else: conNum = number * 10 + NumList[index] branch3 = fun(sum, conNum, index + 1) #保存递归结果到列表 L = [] L.extend(add(digit, '+', branch1)) L.extend(add(digit, '-', branch2)) L.extend(add(digit, '', branch3)) return L; # if __name__ == "__main__": for x in fun(TARGET_SUM, NumList[0], 1): print(x)
运行结果如下:
>>>
1+2+3-4+5+6+78+9
1+2+34-5+67-8+9
1+23-4+5+6+78-9
1+23-4+56+7+8+9
12+3+4+5-6-7+89
12+3-4+5+67+8+9
12-3-4+5-6+7+89
123+4-5+67-89
123+45-67+8-9
123-4-5-6-7+8-9
123-45-67+89
>>>
相关文章的连接:
每个程序员1小时内必须解决的5个编程问题 http://www.codeceo.com/article/5-problems-programmer-1-hour.html https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour https://blog.svpino.com/2015/05/08/solution-to-problem-5-and-some-other-thoughts-about-this-type-of-questions
蔡军生 QQ:9073204 深圳
相关文章推荐
- 每个程序员1小时内必须解决的5个编程问题之难题
- 每个程序员1小时内必须解决的5个编程问题
- 每个程序员1小时内必须解决的5个编程问题(未完成)
- 每个程序员1小时内必须解决的5个编程问题(转)
- 每个程序员1小时内必须解决的5个编程问题
- php版 - 每个程序员1小时内必须解决的5个编程问题
- 每个程序员1小时内必须解决的5个编程问题--解答代码
- 每个程序员1小时内必须解决的5个编程问题--解答代码
- 每个程序员1小时内必须解决的5个编程问题--解答代码
- 每个程序员1小时内必须解决的5个编程问题
- 每个程序员1小时内必须解决的5个编程问题--解答代码
- 每个程序员1小时内必须解决的5个编程问题
- 每个程序员1小时内必须解决的5个编程问题--解答代码
- java学习练习(每个程序员1小时内必须解决的5个编程问题)
- 每个程序员1小时内必须解决的5个编程问题之多种方法
- 每个程序员半小时内必须解决的5个编程问题——php实现
- 每个程序员1小时内必须解决的5个编程问题之多种方法
- 程序员必须1小时内解决的5个编程问题
- 1小时内必须解决的5个编程问题