【问题标题】:Given a non-negative integer N, returns the number of non-negative integers similar to N in Python给定一个非负整数 N,返回类似于 Python 中 N 的非负整数的个数
【发布时间】:2021-01-04 21:52:18
【问题描述】:

开发一个函数:

如果两个非负整数 N 和 M 的十进制表示可以通过重新排列它们的数字彼此获得,则称它们是相似的。请注意,正确的十进制表示不包含前导零。

Class solution { public int solution(int N); }

给定一个非负整数 N,返回类似于 N 的非负整数的个数。

例如,给定 N =1213,该函数应返回 12,因为有十二个整数类似于 1213,即:1123、1132、1213、1231、1312、1321、2113、2131、2311、3112、3121 和 3211

给定 N = 123,该函数应该返回 6,因为有六个整数类似于 123,即:123、132、213、231、312 和 321

给定 N = 100,函数应该返回 1,因为只有一个相似的整数。 001 和 010 都是不正确的整数十进制表示。

如果 N = 0,函数应该返回 1,因为只有一个相似的整数(数字本身)。

目前,我有一个函数可以创建所有排列,尽管对于 N = 1213,我有 12 个以上。我不知道他们是如何得到这个数字的。

def solution(N):
  
   res = [int(x) for x in str(N)] 
   result_perms = [[]]
   
   for n in res:
       new_perms = []
       for perm in result_perms:
         for i in range(len(perm)+1):
           new_perms.append(perm[:i] + [n] + perm[i:])
           result_perms = new_perms
   return result_perms
   

【问题讨论】:

  • 什么确切地是“N = 1213 超过 12”?您的解决方案返回的具体整数是什么? “相似”究竟是什么意思? (我可以猜到,但据我所知,这不是一个数学概念,你应该明确。)请阅读How to Ask

标签: python numbers


【解决方案1】:

itertools 对于这类问题很有用。我的解决方案:

import itertools
def solution(N):
    count = 0
    for i in set(itertools.permutations(str(N))): # we use set() to eliminate duplicates, and cast N to a string to make it iterable
        perm = "".join(i)
        if str(int(perm))==perm and int(perm) >= 0: #check to ensure that we have no 0's at the front of this permutation
            count += 1
    return count

【讨论】:

  • 或者,return sum(1 for e in {''.join(t) for t in permutations(str(n))} if str(int(e))==e)
  • 我肯定会在我的代码中使用它!它更简洁,但更难将 cmets 添加到... 我们确实需要将 set() 应用于排列,以便我们不会两次包含 1123(在 Brandini 的示例中)。
  • {''.join(t) for t in permutations(str(n))} 部分是一个集合。这是一个set comprehension
  • 啊,我明白了!我疲倦的眼睛没有注意到牙套是卷曲的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
相关资源
最近更新 更多