Skip to content

Instantly share code, notes, and snippets.

@akrizs
Last active March 27, 2022 20:31
Show Gist options
  • Save akrizs/54bb6b5a8725b6d850016e3721ad77d1 to your computer and use it in GitHub Desktop.
Save akrizs/54bb6b5a8725b6d850016e3721ad77d1 to your computer and use it in GitHub Desktop.
A set of generators to generate collection of prime, composites, odd, even, fibonacci and squarable numbers...
from math import sqrt
def is_prime(num: int):
for n in range(2,int(num**0.5)+1):
if num%n==0:
return False
return True
def is_composite(num: int):
return not is_prime(num)
def is_odd(num: int):
if (num % 2) == 0:
return False
else:
return True
def is_even(num: int):
return not is_odd(num)
def sqr_root(num: int):
return num ** (1/2)
def squarables(num: int = 1, count: int or None = 100, under: bool = False):
n = num
tick = 1
while True:
if n > 0:
if sqrt(n).is_integer():
yield n
if under:
n -= 1
else:
n += 1
if count:
if tick < count:
tick += 1
else:
break
else:
if under:
n -= 1
else:
n += 1
else:
break
def odds(num: int = 1, count: int or None = 100, under: bool = False):
n = num
tick = 1
while True:
if n > 0:
if is_odd(n):
yield n
if under:
n -= 1
else:
n += 1
if count:
if tick < count:
tick += 1
else:
break
else:
if under:
n -= 1
else:
n += 1
else:
break
def evens(num: int = 1, count: int or None = 100, under: bool = False):
n = num
tick = 1
while True:
if n > 0:
if is_even(n):
yield n
if under:
n -= 1
else:
n += 1
if count:
if tick < count:
tick += 1
else:
break
else:
if under:
n -= 1
else:
n += 1
else:
break
def primes(num: int = 2, count: int or None = 100, under: bool = False):
n = num
tick = 1
while True:
if n > 0:
if is_prime(n):
yield n
if under:
n -= 1
else:
n += 1
if count:
if tick < count:
tick += 1
else:
break
else:
if under:
n -= 1
else:
n += 1
else:
break
def composites(num: int = 2, count: int or None = 100, under: bool = False):
n = num
tick = 1
while True:
if n > 0:
if is_composite(n):
yield n
if under:
n -= 1
else:
n += 1
if count:
if tick < count:
tick += 1
else:
break
else:
if under:
n -= 1
else:
n += 1
else:
break
def fibonaccis(nums: int):
x, y = 0, 1
for _ in range(nums):
x, y = y, x+y
yield x
if __name__ == "__main__":
# Select how many numbers should be in the list generated.
# default count is set to 100, otherwise the generator just runs forever
# and generates endless counts of numbers.
count = 15
sq = [x for x in squarables(count=count)]
od = [x for x in odds(count=count)]
ev = [x for x in evens(count=count)]
pr = [x for x in primes(count=count)]
co = [x for x in composites(count=count)]
fi = [x for x in fibonaccis(count)]
print(sq)
print(od)
print(ev)
print(pr)
print(co)
print(fi)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment