From the course: Programming Foundations: Data Structures

Unlock the full course today

Join today to access over 24,900 courses taught by industry experts.

Solution: Generate binary numbers

Solution: Generate binary numbers - Python Tutorial

From the course: Programming Foundations: Data Structures

Solution: Generate binary numbers

- [Instructor] Let's create a function that returns a list of the first in binary numbers. We'll be using a deck for our implementation. So we'll add that import at the top. (keyboard clacks) First, we'll handle our invalid inputs. If n is less than or equal to zero, we'll simply exit the function and return an empty list. (keyboard clacks) Now, let's take a look at a few binary numbers and see if we can find a pattern. (keyboard clacks) If we observe closely, each binary number is formed by taking the current number and appending a zero to it, and then a one to it. For example, after printing one, we add one, zero and one, one to the sequence, then after processing one, zero, we append one, zero, zero and one, zero, one to the sequence. This pattern repeats for the rest of the binary numbers. We can leverage this pattern using a deck to generate the first n binary numbers. We'll start by initializing our result list and a deck. (keyboard clacks) Since n is at least one, we can add…

Contents