简体   繁体   中英

Yield number into parts smaller than a threshold in Python

Assuming I have a number n=22500 and a threshold t=10000 , I want to have a function that yields: 10000 , 10000 , 2500 .

How do I do this? My non-working attempt because once you go over 20000 it returns numbers larger than 10000.

def chunk(number):
    steps = 10000
    if number > steps:
        yield steps
        yield number - steps
    else:
        yield number

for i in chunk(35000):
   print(i)

# prints (wrongly):
# 10000
# 25000

Or is there a builtin library for this?

I think this can be cleaned up a bit, so check back for edits over the next few minutes, but what about:

def chunk(num, thresh):
    while True:
        if num > thresh:
            num -= thresh
            yield thresh
        else:
            yield num
            break

for x in chunk(22500, 10000):
    print(x)

Output

10000
10000
2500

Edit:

Consider:

def chunk(num, thresh):
    while num:
        to_yield = min(num, thresh)
        yield to_yield
        num -= to_yield

for x in chunk(22500, 10000):
    print(x)

Using division (floor) and modulus operators:

def chunk(number, step):
    for i in range(number // step):
        yield step
    rem = number % step
    if rem:
        yield rem

for i in chunk(22500, step=10000):
    print(i)

10000
10000
2500

You need a loop to make sure it works with any amount:

def chunk(number):
    steps = 10000
    while number > 0:
        yield min(number, steps)
        number -= steps

for i in chunk(35000):
   print(i)

# prints:
# 10000
# 10000
# 10000
# 5000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM