Created
November 19, 2019 08:57
-
-
Save windsting/23247e5925ebff1058e0e6300bdfaf50 to your computer and use it in GitHub Desktop.
7个鸡蛋,放进3个不同的碗,允许有空碗,有多少种放法?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#coding=utf-8 | |
# 7个鸡蛋,放进3个不同的碗,允许有空碗,有多少种放法? | |
# use function `place` to get answer | |
# and `place_non` for **avoid empty bowl** | |
def gen_counts(prev, cur): | |
str = f"{cur}" if prev == "" else f"{prev},{cur}" | |
return str | |
def place(eggs, bowls, counts, lst): | |
if bowls == 1: | |
lst.append(gen_counts(counts, eggs)) | |
return 1 | |
if eggs == 0: | |
lst.append(gen_counts(counts,0)) | |
return 1 | |
count = 0 | |
for i in range(eggs+1): | |
cur_bowl_count = i | |
str_counts = gen_counts(counts, cur_bowl_count) | |
count += place(eggs-i, bowls-1, str_counts, lst) | |
return count | |
def place_non(eggs, bowls, counts, lst): | |
if bowls == 1: | |
lst.append(gen_counts(counts, eggs)) | |
return 1 | |
count = 0 | |
for i in range(1,eggs-bowls+2): | |
cur_bowl_count = i | |
str_counts = gen_counts(counts, cur_bowl_count) | |
count += place_non(eggs-i, bowls-1, str_counts, lst) | |
return count | |
# utility | |
def str2bool(v): | |
if isinstance(v, bool): | |
return v | |
if v.lower() in ('yes', 'true', 't', 'y', '1'): | |
return True | |
elif v.lower() in ('no', 'false', 'f', 'n', '0'): | |
return False | |
else: | |
raise argparse.ArgumentTypeError('Boolean value expected.') | |
import argparse | |
parser = argparse.ArgumentParser(description='X eggs put into Y [avoid/allow] bowls, how many arrangements?') | |
parser.add_argument('X', nargs='?', default=7, type=int, help='the count of eggs') | |
parser.add_argument('Y', nargs='?', default=3, type=int, help='the count of bowls') | |
parser.add_argument('--avoid_empty_bowl', '-a', nargs='?', const=True, default=False, type=str2bool, help='if bowls can be empty') | |
def main(): | |
args = parser.parse_args() | |
print(args) | |
lst = [] | |
func = place | |
if args.avoid_empty_bowl: | |
func = place_non | |
count = func(args.X, args.Y, "", lst) | |
str_empty = "avoid" if args.avoid_empty_bowl else "allow" | |
print(f"count for [{args.X}] eggs and [{args.Y}] [{str_empty} empty] bowls is: {count}") | |
# lst.sort() | |
for e in lst: | |
print(f" {e}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment