首页 > 解决方案 > 延迟排序 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 是您从输入中收到的数字序列。

标签: python-3.x

解决方案


推荐阅读