【问题标题】:Given a list of binary numbers (0s and 1s), determine the number of possible arrangements of distinct binary sequences using given 0s and 1s给定一个二进制数列表(0 和 1),使用给定的 0 和 1 确定不同二进制序列的可能排列数
【发布时间】:2021-10-20 17:32:21
【问题描述】:

给定一个二进制数列表(0 和 1),使用给定的 0 和 1 确定不同二进制序列的可能排列数。

输入格式:

包含 0 和 1 的单行输入

输出格式:

打印一个整数值,表示使用给定的 0 和 1 可能排列的数量

例子:

输入:

0 1 0 1

输出:

6

解释:

对于给定的输入,可能形成的不同二进制序列是 0011、0101、0110、1001、1010、1100。

因此输出为 6。 我已经尝试过了,但出现错误。

import math
c=input().split()
a=0
b=0
for i in c:
  if int(i)==0:
    b+=1
  if int(i)==1:
    a+=1
answer=int(math.factorial(len(c))/(math.factorial(a)*math.factorial(b)))
print(answer,end="")

Click here to see my output

【问题讨论】:

  • @RobbyCornelissen 0!是 1,所以不会除以 0。不过,我同意如果没有看到失败的测试就很难判断。他们answer 的公式是正确的,所以它必须是一个极端情况。
  • 哦,是的,你是对的。
  • 不,一点也不。我尝试了 3 个零,4 个 1,我没有收到任何错误。
  • 这是我的下一个想法。我相对确定发布的代码是正确的。同样,当您为空输入返回 0 时会发生什么。我并不是说那是对的(因为它不是),但我看到不少人试图提出这样的论点......
  • 不,输入没有限制。我们可以采取任何长度。输入字符串没有最大长度。

标签: python string list binary


【解决方案1】:
import math
c=input()
c=list(c)
a=0
b=0
for i in c:
    if int(i)==0:
        a+=1
    if int(i)==1:
        b+=1
answer=int(math.factorial(len(c))/(math.factorial(a)*math.factorial(b)))
print(answer)

【讨论】:

  • @AmazonKing 如果答案有效,请考虑通过单击复选标记来接受。
【解决方案2】:
import math
n=input().split()
a=math.factorial(len(n))//(math.factorial(n.count("1"))*math.factorial(n.count("0")));
print(a,end="")

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
【解决方案3】:
def fact(n):
  if(n==0):
    return 1
  else:
    return n*fact(n-1)
  
myList = list(map(int,input().split()))
a = myList.count(0)
b = myList.count(1)
c = len(myList)
print(int(fact(c)/(fact(a)*fact(b))),end="")

【讨论】:

  • 经典新手错误:您已将 python 的 'list()' 对象替换为来自用户映射到 int 的原始输入数据。用用户数据覆盖列表对象可能会导致神秘的错误。
猜你喜欢
  • 2018-06-12
  • 2023-04-03
  • 2021-02-24
  • 1970-01-01
  • 2015-11-25
  • 2022-11-03
  • 2017-01-03
  • 2015-07-11
相关资源
最近更新 更多