python3 浮点型数值 拆分成指定n个数字之和 ?

比如 8888.666615 需要拆分成 N个浮点类型的和
比如 6 = 1 + 2 +3

阅读 1.4k
1 个回答

import random

判断是否是小数

def is_float(str):

if str.count('.') == 1: #小数有且仅有一个小数点
    left = str.split('.')[0]  #小数点左边(整数位,可为正或负)
    right = str.split('.')[1]  #小数点右边(小数位,一定为正)
    lright = '' #取整数位的绝对值(排除掉负号)
    if str.count('-') == 1 and str[0] == '-': #如果整数位为负,则第一个元素一定是负号
        lright = left.split('-')[1]
    elif str.count('-') == 0:
        lright = left
    else:
       return True
    if right.isdigit() and lright.isdigit(): #判断整数位的绝对值和小数位是否全部为数字
       return True
    else:
       return  False
else:
    return False

数值切分为n个数之和

def num_pieces(num,lenght):

all_list = []
ot = list(range(1, lenght + 1))[::-1]
b = is_float(str(num))
if num <= lenght:
    b = True
if b :
    for i in range(lenght-1):
        n = round(random.uniform(1, num-ot[i]),2)
        all_list.append(n)
        num -= n
    all_list.append(round(num,2))
else:
    for i in range(lenght - 1):
        n = random.radnint(1, num - ot[i])
        all_list.append(n)
        num -= n
    all_list.append(num)
return all_list
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进