python - 取一个数组并返回 3 个相等的数组,如果该数组不能被 3 整除,则增加较小数组的大小?

标签 python

我有一个无法解决的挑战:

Create​ ​a​ ​function​ ​that​ ​accepts​ ​a​ ​single​ ​array​ ​as​ ​an​ ​argument.​ ​Given​ ​an​ ​array​ ​of​ ​integers,​ ​x,​ ​sort x​ ​and​ ​split​ ​the​ ​integers​ ​into​ ​three​ ​smaller​ ​arrays​ ​of​ ​equal​ ​length.​ ​If​ ​the​ ​length​ ​of​ ​x​ ​is​ ​not​ ​evenly divisible​ ​by​ ​three,​ ​increase​ ​the​ ​size​ ​of​ ​the​ ​smaller​ ​arrays​ ​by​ ​one​ ​starting​ ​from​ ​the​ ​first​ ​array.​ ​The function​ ​should​ ​return​ ​an​ ​array​ ​of​ ​arrays. Example: # myArry ​= ​[2,1,3,4,7,5,9,6,8,13,12,11,10,0,15,16,14] # Output​ ​=​ ​[​ ​[0,​ ​1,​ ​2,​ ​3,​ ​4,​ ​5],​ ​[6,​ ​7,​ ​8,​ ​9,​ ​10,​ ​11],​ ​[12,​ ​13,​ ​14,​ ​15,​ ​16]​ ​] –

我有一个解决方案,如果数组长度不大于 3,它就不起作用。我也觉得有一种更短的写法。

a = [2,1,3,4,7,5,9,8,12,11,10,0,15,16,14]
b = [2,1,3,4,7,5,9,8,12,11,10,0,15,16]
c = [2,1,3,4,7,5,9,8,12,11,10,0,15]
d = [1]

def myfunc(ar):
    length = len(ar)
    s = sorted(ar)
    n3 = length//3 
    if(length % 3 == 0):
        return [s[index:index+n3] for index in range(0, length, n3)]
    else:
        num = (len(b) // 3 +1)
        A, B, C = [s[index:index+num] for index in range(0, length, num)]
        if(len(C) != len(A)): 
            C.append(C[-1]+1)
        return A,B,C
    return s

print(myfunc(a)) 
print(myfunc(b))
print(myfunc(c))[cannot split an array with a length less than 3 by n][1]

示例:

输入

myArry ​= ​[2,1,3,4,7,5,9,6,8,13,12,11,10,0,15,16,14]

输出

​[​ ​[0,​ ​1,​ ​2,​ ​3,​ ​4,​ ​5],​ ​[6,​ ​7,​ ​8,​ ​9,​ ​10,​ ​11],​ ​[12,​ ​13,​ ​14,​ ​15,​ ​16]​ ​] 

最佳答案

在您的帮助下,我找到了可行的解决方案!

import numpy as np

def myfunc(ar):
    splited = np.array_split(sorted(ar), 3)
    A,B,C = [x.tolist() for x in splited]
    if(len(C) != len(A)): 
        C.append(C[-1]+1)
        if(len(C) != len(B)):
            B.append(B[-1]+1)

    return A,B,C

感谢@igorkf

关于python - 取一个数组并返回 3 个相等的数组,如果该数组不能被 3 整除,则增加较小数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886868/

相关文章:

python - python中的多处理-forkserver进程从父进程继承了什么?

扩展 kwargs 时广播/循环值的 Pythonic 方式

Python:如何比较来自 fasta 文件的多个序列?

Python线程 - 内部缓冲区错误 - 内存不足

python如何知道当前线程是否持有锁

python - 没有在 Python 中分组的正则表达式和 OR 运算符?

页面上的 Javascript 阻止 Selenium 检测某些框架和元素

Python:在数组中填充多边形区域

python - GAE 应用程序是否保留其发送的电子邮件的日志?

python - 为 mysql-python (MySQLdb) 更改 django 中的 CLIENT_FOUND_ROWS 标志?