From 8e9cbfd87f3b5a40e171c869695e0e3d7f97a654 Mon Sep 17 00:00:00 2001 From: Mia von Steinkirch Date: Mon, 13 May 2019 16:08:11 -0700 Subject: [PATCH] more --- interview_cake/math/fib.py | 36 ++++++++++++++++++++++++++++ interview_cake/math/recursive_per.py | 32 +++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 interview_cake/math/fib.py create mode 100644 interview_cake/math/recursive_per.py diff --git a/interview_cake/math/fib.py b/interview_cake/math/fib.py new file mode 100644 index 0000000..8654152 --- /dev/null +++ b/interview_cake/math/fib.py @@ -0,0 +1,36 @@ +#!/bin/python + +""" +Write a function fib() that takes an integer nn and returns the nnth Fibonacci number. +""" + +# this is O(2^n) +def fib(n): + if n in [1, 0]: + return n + return fib(n - 1) + fib(n - 2) + + +print fib(10) + + +# this is O(n) +def fib(n): + if n < 0: + raise ValueError('Index was negative. No such thing as a ' + 'negative index in a series.') + elif n in [0, 1]: + return n + + prev_prev = 0 # 0th fibonacci + prev = 1 # 1st fibonacci + + for _ in range(n - 1): + current = prev + prev_prev + prev_prev = prev + prev = current + + return current + + +print fib(10) \ No newline at end of file diff --git a/interview_cake/math/recursive_per.py b/interview_cake/math/recursive_per.py new file mode 100644 index 0000000..0c9d00f --- /dev/null +++ b/interview_cake/math/recursive_per.py @@ -0,0 +1,32 @@ +#!/bin/python + +""" +Write a recursive function for generating all permutations of an input string. Return them as a set. +""" + +def get_permutations(string): + + if len(string) < 2: + return set([string]) + + all_chars_except_last = string[:-1] + last_char = string[-1] + + permutations_of_all_chars_except_last = get_permutations(all_chars_except_last) + + permutations = set() + for permutation_of_all_chars_except_last in permutations_of_all_chars_except_last: + for position in range(len(all_chars_except_last) + 1): + permutation = ( + permutation_of_all_chars_except_last[:position] + + last_char + + permutation_of_all_chars_except_last[position:] + ) + permutations.add(permutation) + + + return permutations + + +str = "abcd" +print get_permutations(str) \ No newline at end of file