Codewars--How many numbers III? (python)

14 篇文章 0 订阅
13 篇文章 0 订阅

How many numbers III?

难度系数 4kyu

这题目一开始没看懂什么意思,但感觉应该是个挺有意思的题目就直接跳过查看答案,看完答案才明白题目的意思,本题引用 yojimboz的答案,https://www.codewars.com/users/yojimboz

题目的意思大概是输入两个数,第一个为数字之和,第2个为由n位数组成,输出为有多少个这样的n位数,最小值是多少,最大值是多少。

题目:
We want to generate all the numbers of three digits that:
the value of adding their corresponding ones(digits) is equal to 10.
their digits are in increasing order (the numbers may have two or more equal contiguous digits)
The numbers that fulfill the two above constraints are: 118, 127, 136, 145, 226, 235, 244, 334
Make a function that receives two arguments:
the sum of digits value
the amount of desired digits for the numbers
The function should output an array with three values: [1,2,3]
1 - the total amount of all these possible numbers
2 - the minimum number
3 - the maximum numberwith

The example given above should be:

find_all(10, 3) == [8, 118, 334]
If we have only one possible number as a solution, it should output a result like the one below:

find_all(27, 3) == [1, 999, 999]
If there are no possible numbers, the function should output the empty array.

find_all(84, 4) == []
The number of solutions climbs up when the number of digits increases.

find_all(35, 6) == [123, 116999, 566666]

代码:
主要采用系统自带的itertools工具包中的combinations_with_replacement 函数,它可以十分方便的遍历这n位数,如果数字和等于给定值则保存! 对就是这么简单!不看不知道,一看发现自己懂得太少!!

from itertools import combinations_with_replacement

def find_all(sum_dig, digs):
    combs = combinations_with_replacement(list(range(1, 10)), digs) #组合
    target = [''.join(str(x) for x in list(comb)) for comb in combs if sum(comb) == sum_dig]
    if not target:
        return []
    return [len(target), int(target[0]), int(target[-1])]   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值