python-3.x - 延迟排序 HackerRank Python
问题描述
我是编码新手,因此我编写的以下代码可能不正确或次优。但是,我遇到的问题是我不理解输入,因此无法运行代码(我只使用自定义输入对其进行了测试)。
问题的本质是你有一些数字序列并且你想单调地排列序列(非递减或非递增)。你通过随机洗牌来做到这一点。你需要多少次随机播放才能通过随机随机播放进入单调序列?你可以在这里找到问题,下面是我的代码:
#!/bin/python3 ------ The following import is given in the prompt
import os
import sys
# Complete the solve function below. Here is my code below
def solve(P):
P.sort()
correct = P
count = []
i = 0
# Here I am trying to calculate the number of ways to get the desired monotonic sequence
# I count the number of repeated numbers in the sequence as separate items in a list
for j in range(i,len(correct)):
if correct[i] != correct[j] or i == len(correct) - 1:
count.append(j-i)
i = j
j = len(correct)
else:
j = j + 1
summ = 0
for k in range(len(count)):
summ = summ + count[k]
if summ == len(correct):
i = len(correct)
poss = [1]*len(count)
for k in range(len(count)):
for l in range(1,count[k]+1):
poss[k] = poss[k]*l
possible = 1
for x in poss:
possible = possible * x
# This is calculating the number of different permutations of n distinct elements
total = 1
n = len(correct)
for i in range(1,n+1):
total = total * i
# Calculating the probability to the 6th decimal place
probability = float(possible / total)
expected = round(1/probability, 6)
print(expected)
# The following code is given in the prompt to input the test cases
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
P_count = int(input())
P = list(map(int, input().rstrip().split()))
result = solve(P)
fptr.write(str(result) + '\n')
fptr.close()
在我的代码中,我只是假设 P 是您从输入中收到的数字序列。
解决方案
推荐阅读
- java - 像 Spotify 这样的应用程序如何在系统阻塞和睡眠时保持音乐播放
- c - 从包含整数的文件中读取一行
- loops - ansible 循环遍历文件列表并检查文件是否存在,如果不下载它
- php - woocommerce 无法为 function.php 生成通用函数
- java - java教科书帮助中的推回流示例。到底是怎么回事?
- assembly - 代码正在运行,但没有在 emu8086 中显示任何输出
- javascript - 尝试在反应应用程序中连接到 mongodb 时,应用程序崩溃并出现错误:无法获取未定义或空引用的属性“替换”
- javascript - React-select 不渲染数据
- lua - 为什么stdin在显示文本时返回错误?
- ios - 如何在 ARKit 中放置自定义对象(.scn)?