Skip to content

Instantly share code, notes, and snippets.

@junetech
Created December 4, 2019 13:50
Show Gist options
  • Save junetech/04c9f25e724074721dac52eb8396bd16 to your computer and use it in GitHub Desktop.
Save junetech/04c9f25e724074721dac52eb8396bd16 to your computer and use it in GitHub Desktop.
Python yield example: integer combination generator
from typing import List, Any, Generator
def minmaxpartition(_sum: int, _count: int, _min: int, _max: int
) -> Generator[List[Any], None, None]:
if _min > _max:
yield []
return
if _sum < _count * _min:
yield []
return
elif _sum > _count * _max:
yield []
return
if _count == 1:
yield [_sum]
return
for j in range(_max, _min-1, -1):
for return_list in minmaxpartition(_sum-j, _count-1, _min, j):
if return_list:
yield [j] + return_list
def main():
_sum = 51
_numbers = 3
_min = 14
_max = 19
for return_list in minmaxpartition(_sum, _numbers, _min, _max):
print(return_list)
if __name__ == "__main__":
print("main function begins")
main()
print("main function ended without hassle")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment