mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-22 16:31:15 -04:00
Add some cool queue, stacks, strings, math, bit manipulation examples (#35)
This commit is contained in:
parent
f3ee2cdf52
commit
0f455a0322
24 changed files with 932 additions and 13 deletions
|
@ -0,0 +1,20 @@
|
|||
## math and logic
|
||||
|
||||
<br>
|
||||
|
||||
|
||||
```python
|
||||
python3 fibonacci.py
|
||||
|
||||
Testing fibonacci
|
||||
Fibonacci of 10: 55
|
||||
```
|
||||
|
||||
<br>
|
||||
|
||||
```python
|
||||
python playing_with_math.py
|
||||
|
||||
Greatest common divider of 21 and 7 is 7
|
||||
Prime factors of 21 are [3, 7]
|
||||
```
|
16
math_and_logic/fibonacci.py
Normal file
16
math_and_logic/fibonacci.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
def fibonacci(n):
|
||||
""" Calculate the nth Fibonacci number """
|
||||
if n == 0 or n == 1:
|
||||
return n
|
||||
return fibonacci(n - 1) + fibonacci(n - 2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
print('Testing fibonacci')
|
||||
n = 10
|
||||
print(f'Fibonacci of {n}: {fibonacci(n)}')
|
50
math_and_logic/playing_with_math.py
Normal file
50
math_and_logic/playing_with_math.py
Normal file
|
@ -0,0 +1,50 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
import math
|
||||
import random
|
||||
|
||||
|
||||
def find_greatest_common_divider(a, b) -> int:
|
||||
'''Implements the greatest common divider algorithm '''
|
||||
|
||||
while(b != 0):
|
||||
result = b
|
||||
a, b = b, a % b
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def _is_prime(number) -> bool:
|
||||
'''Check if a number is prime '''
|
||||
|
||||
if number < 2:
|
||||
return False
|
||||
|
||||
for i in range(2, int(math.sqrt(number))):
|
||||
if number % i == 0:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def find_prime_factors(number) -> list:
|
||||
'''Find prime factors of a number '''
|
||||
|
||||
divisors = [d for d in range(2, number//2 + 1) if number % d == 0]
|
||||
primes = [d for d in divisors if _is_prime(d)]
|
||||
|
||||
return primes
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
n1 = 21
|
||||
n2 = 7
|
||||
|
||||
print(f'Greatest common divider of {n1} and {n2} is {find_greatest_common_divider(n1, n2)}')
|
||||
print(f'Prime factors of {n1} are {find_prime_factors(n1)}')
|
||||
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue