Last active
September 23, 2021 12:53
-
-
Save wesleyel/a085b72eaa46d981e1fda690da4a5f8e to your computer and use it in GitHub Desktop.
calculate combinatorial problems
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
# This is a sample Python script. | |
# You can use it to calculate combinatorial problems | |
# magicwenli on 2021.09.23 | |
import argparse | |
import math | |
from fractions import Fraction | |
def combA(arguments: list): | |
sums = 0 | |
for i in range(len(arguments) // 2): | |
a = arguments[i] | |
b = arguments[i + 1] | |
if a < b: # a是底数 | |
a, b = b, a | |
sums += math.comb(a, b) | |
return sums | |
def main(): | |
# Create the parser | |
my_parser = argparse.ArgumentParser(description='Calculate combs', | |
epilog="Try: python main.py 8 2 5 2 -d 13 2. And you may get 19/39.") | |
# Add the arguments | |
my_parser.add_argument('up', | |
nargs='+', | |
type=int, | |
help='upper part of fraction, use a list like `3 1 2 1`') | |
my_parser.add_argument('-d', | |
'--down', | |
nargs='+', | |
type=int, | |
help='lower part of fraction, same as up') | |
# Execute parse_args() | |
args = my_parser.parse_args() | |
print(f"ups: {args.up}\ndowns: {args.down}\n") | |
ups = combA(args.up) | |
downs = 0 | |
if args.down is None: | |
print(ups) | |
return ups | |
else: | |
downs = combA(args.down) | |
print(f"{ups}/{downs} =") | |
print(Fraction(ups, downs)) | |
return Fraction(ups, downs) | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment