From 2fa4c62d886249fa86ab209d8e758110be7b0f71 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Sun, 4 Oct 2020 12:19:28 +0300 Subject: [PATCH] Add geometric_progression --- snippets/geometric_progression.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 snippets/geometric_progression.md diff --git a/snippets/geometric_progression.md b/snippets/geometric_progression.md new file mode 100644 index 000000000..549ba46df --- /dev/null +++ b/snippets/geometric_progression.md @@ -0,0 +1,24 @@ +--- +title: geometric_progression +tags: math,list,intermediate +--- + +Initializes a list containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`. +Returns an error if `step` equals `1`. + +- Use `range()`, `math.log()` and `math.floor()` and a list comprehension to create a list of the appropriate length, applying the step for each element. +- Omit the second argument, `start`, to use a default value of `1`. +- Omit the third argument, `step`, to use a default value of `2`. + +```py +from math import floor, log + +def geometric_progression(end, start = 1, step = 2): + return [start * step ** i for i in range(0, floor(log(end/start) / log(step)) + 1)] +``` + +```py +geometric_progression(256) # [1, 2, 4, 8, 16, 32, 64, 128, 256] +geometric_progression(256, 3) # [3, 6, 12, 24, 48, 96, 192] +geometric_progression(256, 1, 4) # [1, 4, 16, 64, 256] +```