diff --git a/python-coding-interview-tips/README.md b/python-coding-interview-tips/README.md new file mode 100644 index 0000000000..f7a9655010 --- /dev/null +++ b/python-coding-interview-tips/README.md @@ -0,0 +1,32 @@ +# How to Stand Out in a Python Coding Interview + +This folder contains sample code for the Real Python tutorial [How to Stand Out in a Python Coding Interview](https://realpython.com/python-coding-interview-tips/). + +## Setup + +The scripts only use Python's standard library, so there's nothing to install. You need Python 3.7 or later. The code was tested on Python 3.15. + +## Usage + +Each script matches a section of the tutorial. Run any of them with Python: + +```sh +$ python enumerate_fizzbuzz.py +``` + +| Script | Section | +| --- | --- | +| `enumerate_fizzbuzz.py` | Iterate With `enumerate()` Instead of `range()` | +| `comprehensions_vs_map_filter.py` | Use List Comprehensions Instead of `map()` and `filter()` | +| `debug_with_breakpoint.py` | Debug With `breakpoint()` Instead of `print()` | +| `fstrings.py` | Format Strings With F-Strings | +| `sorting.py` | Sort Complex Lists With `sorted()` | +| `unique_words.py` | Store Unique Values With Sets | +| `generators.py` | Save Memory With Generators | +| `dict_defaults.py` | Define Default Values in Dictionaries With `.get()` and `.setdefault()` | +| `grades_defaultdict.py` | Handle Missing Dictionary Keys With `collections.defaultdict()` | +| `word_counter.py` | Count Hashable Objects With `collections.Counter` | +| `string_constants.py` | Access Common String Groups With `string` Constants | +| `permutations_combinations.py` | Generate Permutations and Combinations With `itertools` | + +`debug_with_breakpoint.py` drops you into `pdb`. Type `c` to continue, or run it with `PYTHONBREAKPOINT=0` to skip the breakpoint. diff --git a/python-coding-interview-tips/comprehensions_vs_map_filter.py b/python-coding-interview-tips/comprehensions_vs_map_filter.py new file mode 100644 index 0000000000..cc10ad9161 --- /dev/null +++ b/python-coding-interview-tips/comprehensions_vs_map_filter.py @@ -0,0 +1,16 @@ +numbers = [4, 2, 1, 6, 9, 7] + + +def square(x): + return x * x + + +def is_odd(x): + return bool(x % 2) + + +print(list(map(square, numbers))) +print([square(x) for x in numbers]) + +print(list(filter(is_odd, numbers))) +print([x for x in numbers if is_odd(x)]) diff --git a/python-coding-interview-tips/debug_with_breakpoint.py b/python-coding-interview-tips/debug_with_breakpoint.py new file mode 100644 index 0000000000..5de2a3a210 --- /dev/null +++ b/python-coding-interview-tips/debug_with_breakpoint.py @@ -0,0 +1,7 @@ +# Some complicated code with bugs +numbers = [45, 22, 14, 65, 97, 72] +total = sum(numbers) + +breakpoint() + +print(f"The total is {total}") diff --git a/python-coding-interview-tips/dict_defaults.py b/python-coding-interview-tips/dict_defaults.py new file mode 100644 index 0000000000..5f734aef9c --- /dev/null +++ b/python-coding-interview-tips/dict_defaults.py @@ -0,0 +1,20 @@ +cowboy = {"age": 32, "horse": "mustang", "hat_size": "large"} + +if "name" in cowboy: + name = cowboy["name"] +else: + name = "The Man with No Name" +print(repr(name)) + +name = cowboy.get("name", "The Man with No Name") +print(repr(name)) + +if "name" not in cowboy: + cowboy["name"] = "The Man with No Name" +name = cowboy["name"] +print(repr(name)) + +cowboy = {"age": 32, "horse": "mustang", "hat_size": "large"} +name = cowboy.setdefault("name", "The Man with No Name") +print(repr(name)) +print(cowboy) diff --git a/python-coding-interview-tips/enumerate_fizzbuzz.py b/python-coding-interview-tips/enumerate_fizzbuzz.py new file mode 100644 index 0000000000..d5c5e026df --- /dev/null +++ b/python-coding-interview-tips/enumerate_fizzbuzz.py @@ -0,0 +1,28 @@ +def fizzbuzz_range(numbers): + for i in range(len(numbers)): + if numbers[i] % 3 == 0 and numbers[i] % 5 == 0: + numbers[i] = "fizzbuzz" + elif numbers[i] % 3 == 0: + numbers[i] = "fizz" + elif numbers[i] % 5 == 0: + numbers[i] = "buzz" + return numbers + + +def fizzbuzz_enumerate(numbers): + for i, num in enumerate(numbers): + if num % 3 == 0 and num % 5 == 0: + numbers[i] = "fizzbuzz" + elif num % 3 == 0: + numbers[i] = "fizz" + elif num % 5 == 0: + numbers[i] = "buzz" + return numbers + + +print(fizzbuzz_range([45, 22, 14, 65, 97, 72])) +print(fizzbuzz_enumerate([45, 22, 14, 65, 97, 72])) + +numbers = [45, 22, 14, 65, 97, 72] +for i, num in enumerate(numbers, start=52): + print(i, num) diff --git a/python-coding-interview-tips/fstrings.py b/python-coding-interview-tips/fstrings.py new file mode 100644 index 0000000000..60504c9d80 --- /dev/null +++ b/python-coding-interview-tips/fstrings.py @@ -0,0 +1,5 @@ +def get_name_and_decades(name, age): + return f"My name is {name} and I'm {age / 10:.5f} decades old." + + +print(repr(get_name_and_decades("Maria", 31))) diff --git a/python-coding-interview-tips/generators.py b/python-coding-interview-tips/generators.py new file mode 100644 index 0000000000..79a6dc1864 --- /dev/null +++ b/python-coding-interview-tips/generators.py @@ -0,0 +1,3 @@ +print(sum([i * i for i in range(1, 1001)])) +print(sum((i * i for i in range(1, 1001)))) +print(sum(i * i for i in range(1, 1001))) diff --git a/python-coding-interview-tips/grades_defaultdict.py b/python-coding-interview-tips/grades_defaultdict.py new file mode 100644 index 0000000000..187a11a428 --- /dev/null +++ b/python-coding-interview-tips/grades_defaultdict.py @@ -0,0 +1,28 @@ +from collections import defaultdict + +grades = [ + ("elliot", 91), + ("neelam", 98), + ("bianca", 81), + ("elliot", 88), +] + +student_grades = {} +for name, grade in grades: + if name not in student_grades: + student_grades[name] = [] + student_grades[name].append(grade) +print(student_grades) + +student_grades = defaultdict(list) +for name, grade in grades: + student_grades[name].append(grade) +print(student_grades) + +# Membership tests and .get() don't trigger the default factory. +print("james" in student_grades) +print(student_grades.get("james")) + +# Accessing a missing key does, and it inserts the key. +print(student_grades["james"]) +print("james" in student_grades) diff --git a/python-coding-interview-tips/permutations_combinations.py b/python-coding-interview-tips/permutations_combinations.py new file mode 100644 index 0000000000..9d68347928 --- /dev/null +++ b/python-coding-interview-tips/permutations_combinations.py @@ -0,0 +1,6 @@ +import itertools + +friends = ["Monique", "Ashish", "Devon", "Bernie"] + +print(list(itertools.permutations(friends, r=2))) +print(list(itertools.combinations(friends, r=2))) diff --git a/python-coding-interview-tips/sorting.py b/python-coding-interview-tips/sorting.py new file mode 100644 index 0000000000..1cd5d8e6a0 --- /dev/null +++ b/python-coding-interview-tips/sorting.py @@ -0,0 +1,9 @@ +print(sorted([6, 5, 3, 7, 2, 4, 1])) +print(sorted(["cat", "dog", "cheetah", "rhino", "bear"], reverse=True)) + +animals = [ + {"type": "penguin", "name": "Stephanie", "age": 8}, + {"type": "elephant", "name": "Devon", "age": 3}, + {"type": "puma", "name": "Moe", "age": 5}, +] +print(sorted(animals, key=lambda animal: animal["age"])) diff --git a/python-coding-interview-tips/string_constants.py b/python-coding-interview-tips/string_constants.py new file mode 100644 index 0000000000..394d547034 --- /dev/null +++ b/python-coding-interview-tips/string_constants.py @@ -0,0 +1,26 @@ +import string + +print("A" > "a") + + +def is_upper(word): + for letter in word: + if letter not in string.ascii_uppercase: + return False + return True + + +def is_upper_all(word): + return all(letter in string.ascii_uppercase for letter in word) + + +print(is_upper("Thanks Geir")) +print(is_upper("LOL")) +print(is_upper_all("Thanks Geir")) +print(is_upper_all("LOL")) + +# .isupper() ignores characters that aren't letters, such as spaces. +print("HI ROBERT".isupper()) +print(is_upper("HI ROBERT")) + +print(repr(string.ascii_uppercase)) diff --git a/python-coding-interview-tips/unique_words.py b/python-coding-interview-tips/unique_words.py new file mode 100644 index 0000000000..b5303e15a9 --- /dev/null +++ b/python-coding-interview-tips/unique_words.py @@ -0,0 +1,39 @@ +import random + +all_words = "all the words in the world".split() + + +def get_random_word(): + return random.choice(all_words) + + +def get_unique_words_bad(): + """Store values in a list, then convert the list into a set.""" + words = [] + for _ in range(1000): + words.append(get_random_word()) + return set(words) + + +def get_unique_words_worse(): + """Check every new word against the whole list: O(N²).""" + words = [] + for _ in range(1000): + word = get_random_word() + if word not in words: + words.append(word) + return words + + +def get_unique_words_good(): + """Use a set from the start: O(N).""" + words = set() + for _ in range(1000): + words.add(get_random_word()) + return words + + +# The order of the words may differ from run to run. +print(get_unique_words_bad()) +print(get_unique_words_worse()) +print(get_unique_words_good()) diff --git a/python-coding-interview-tips/word_counter.py b/python-coding-interview-tips/word_counter.py new file mode 100644 index 0000000000..67bf44830a --- /dev/null +++ b/python-coding-interview-tips/word_counter.py @@ -0,0 +1,6 @@ +from collections import Counter + +words = "if there was there was but if there was not there was not".split() +counts = Counter(words) +print(counts) +print(counts.most_common(2))