Luninariel

Week 5 examples

Sep 23rd, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. def even_numbers(limit):
  2.     x = 0
  3.     while x < limit:
  4.         yield x
  5.         x += 2
  6.  
  7. def factors(x):
  8.     p = 2
  9.     while p <=  x:
  10.         if x % p ==0:
  11.             yield p
  12.         p += 1
  13.  
  14. def prime_factors(x):
  15.     p = 2
  16.     while p <= x:
  17.         if x % p == 0 and len(factors(x)) == 2:
  18.             yield p
  19.         p += 1
  20.  
  21. def factorial(x):
  22.     if x == 0:
  23.         return 1
  24.     return factorial(x - 1) * x
  25.  
  26. def permutation(s, x):
  27.     if len(s) == 1:
  28.         return tuple(s)
  29.     if len(s) == 0:
  30.         return ()
  31.     s = list(s)
  32.     selection = x % len(s)
  33.     head = (s[selection],)
  34.     del s[selection]
  35.     return head + permutation(set(s), x // (len(s)+1))
  36.  
  37. def permutations(s):
  38.     x = factorial(len(s)) - 1
  39.     while x >= 0:
  40.         yield permutation(s, x)
  41.         x -= 1
Advertisement
Add Comment
Please, Sign In to add comment